Jason
Jason

Reputation: 1141

Disable a button after one click in Vue.js

I am building out a new app with Vue.js and have come across what I thought would be a simple problem but can not find a solution yet.

I have a question with three answers. I only want the user to be able to click an answer once which I know I can use @click.once but I need to let the user know it is no longer clickable in the UI. I have tried some like <button :disabled="submitted" @click="checkAnswer('q1','3'), submitted = true"></button> but this disables all three buttons at the same time. Can someone please show me how to disable a button once the user has clicked it and keep it independent from other buttons? I really appreciate any help.

HTML:

<ul>
    <li><button class="btn blue" @click="checkAnswer('q1','1')">Answer 1 for q1</button></li>
    <li><button class="btn blue" @click="checkAnswer('q1','2')">Answer 2 for q1</button></li>
    <li><button class="btn blue" @click="checkAnswer('q1','3')">Answer 2 for q1</button></li>
</ul>

Code:

export default {
name: 'Questions',
props: ['clue'],
data(){
    return {
        feedback: null,
        answer: null,
        answers: {
            q1: '2',
            q2: '1',
            q3: '3'
        }
    }
},
 methods: {
    checkAnswer(q, a) {
        if(a == this.answers[q]){
            this.answer = "Congrats!"
        } else {
            this.answer = "Sorry that was the wrong answer."
        }
    }
}
}

Upvotes: 3

Views: 7798

Answers (1)

Roy J
Roy J

Reputation: 43881

Pass $event as the third argument, then in the handler, event.target.disabled = true

This is really the quick and dirty approach, which is ok as long as that's the end of the road for the buttons. A more robust approach would be to make a component to use for each of the buttons, and have a state variable for whether it is disabled.

Upvotes: 10

Related Questions