How to disable a button after clicking a button using vue.js

送分小仙女□ 提交于 2019-12-08 05:30:24

问题


I am making a voting application. I want to disable the button once clicking the voting button. How to disable the button.

template

  <v-btn
   v-for="choice in data.choices"
   @click="doVote(choice.id)"
   color="success"
   v-bind:key="choice.id">
   votes: {{ choice.votes }}
  </v-btn>

script

  data () {
    return {
      vote: null,
      questions: [],
    }
  },

  methods: {
    fetchData () {
      this.$request.questions.list().then(res => {
        this.questions = res.data.results
      })
    },

    // add votes
    doVote (vote) {
      if (!vote) {
        return
      }
      this.$request.questions.vote(vote).then(res => {
        this.fetchData()
      })
    },

  mounted () {
    this.fetchData()
  },

回答1:


v-btnhas a disabled property you can use; One way to do this could be create a clicked field to record all buttons you've clicked and check whether a specific button is in the clicked array:

<v-btn
   :disabled="clicked.includes(choice.id)"
   v-for="choice in data.choices"
   @click="doVote(choice.id)"
   color="success"
   v-bind:key="choice.id">
   votes: {{ choice.votes }}
</v-btn>

In data, initialize clicked as an empty array:

data () {
    return {
      vote: null,
      questions: [],
      clicked: []
    }
  }

Then in the doVote method, push the choice.id to clicked array when the event is fired:

doVote (vote) {
  this.clicked.push(vote)
  if (!vote) {
    return
  }
  this.$request.questions.vote(vote).then(res => {
    this.fetchData()
  })
}



回答2:


The simplest thing do is set a variable when the voting button is pressed and then bind it to the buttons 'disabled' property:

v-bind:disabled="hasVoted"



回答3:


You can add an another variable (in this case votes) which will record the votes and then you can use it to determine if the button should be disabled (see votes.indexOf(choice.id) !== -1).

template:

  <v-btn
   :disabled="votes.indexOf(choice.id) !== -1"
   v-for="choice in data.choices"
   @click="doVote(choice.id)"
   color="success"
   v-bind:key="choice.id">
   votes: {{ choice.votes }}
  </v-btn>

script

  data () {
    return {
      votes: [],
      vote: null,
      questions: [],
    }
  },

  methods: {
    fetchData () {
      this.$request.questions.list().then(res => {
        this.questions = res.data.results
      })
    },

    // add votes
    doVote (vote) {
      if (!vote) {
        return
      }
      this.$request.questions.vote(vote).then(res => {
        this.fetchData()
        this.votes.push(vote);
      })
    },

  mounted () {
    this.fetchData()
  },


来源:https://stackoverflow.com/questions/50808465/how-to-disable-a-button-after-clicking-a-button-using-vue-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!