Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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()
  },
like image 613
nk18 Avatar asked Nov 28 '22 22:11

nk18


2 Answers

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"
like image 152
Victor Behar Avatar answered Dec 04 '22 08:12

Victor Behar


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()
  })
}
like image 27
Psidom Avatar answered Dec 04 '22 07:12

Psidom