Steps to deactivate a button upon clicking in vue.js

I need assistance with my voting application. I am looking to implement a feature that disables the voting button after it has been clicked. Can someone provide guidance on how to achieve this?

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()
  },

Answer №1

To easily control the voting button, one can assign a variable when the button is clicked and connect it to the 'disabled' attribute of the button:

v-bind:disabled="hasVoted"

Answer №2

Utilize the disabled property of the v-btn component effectively by tracking the clicked buttons in an array. You can achieve this by creating a clicked field to monitor the clicked buttons and disable them accordingly:

<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>

Initially, define clicked as an empty array in the data section:

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

Then, inside the doVote method, add the choice.id to the clicked array when the button is clicked:

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

Answer №3

To enhance functionality, you can introduce another variable (such as votes) to track user votes. This variable can then be used to determine whether the button should be disabled (votes.indexOf(choice.id) !== -1).

Here is an example 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>

And the corresponding script:

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

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

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

  mounted () {
    this.fetchData()
  },

Answer №4

While facing the same issue, I came up with a solution that involves creating an additional array to track clicks, as suggested in previous responses. By using the Array.prototype.some() method, you can determine which buttons to disable by binding the disabled property of your v-btn component like this:

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

I want to credit Michael's response on this SO question for helping me find this solution.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for preventing the use of eval when invoking various functions

Here's a snippet of code I've been using that involves the use of eval. I opted for this approach as it seemed like the most straightforward way to trigger various factory functions, each responsible for different web service calls. I'm awa ...

Sending information from a rails controller to a react component

Wondering how to pass the example @post = Post.all from the controller to React component props while integrating Rails with React via Webpacker. Is it necessary to do this through an API or is there another way? ...

Creating dynamic visual elements on a webpage using HTML: Video

As I continue to learn HTML, CSS, and JavaScript to create a basic website for educational purposes, I have successfully embedded a video stored in my drive using the video element on an HTML page. However, I now aim to also display the video's title, ...

How to use node.js to add JSON data to a JSON file without using an array?

I'm trying to update a JSON file without using an array with FS. The desired format of the file should be: { "roll.705479898579337276.welcomemessage": "There is a welcome message here", "roll.726740361279438902.welcome ...

Displaying a sub-menu for specific menu options to fetch content using routes in ReactJS

Currently, I am in the process of learning the React JavaScript library. My goal is to develop a basic web application that consists of a menu, submenu, and content sections. For this project, I am using react 15.0.2, react-router 2.4.0, babel 6.5.2, and w ...

Is it possible to trigger an event just once?

Is there a way to ensure an event only fires once? I recently discovered that using .one seems to do the trick. ...

How to showcase elements[i] from an array using React

I need to cycle through an array of objects and display each item in a component, with the prop being the index number of the array item. This is the snippet of code I have: import React from 'react'; import './projecten.scss'; import ...

Bi-weekly Calendar Gathering

I am able to get my events sorted by day with the following code: daysOfWeek: [2], However, I have not been able to find any information in the documentation on how to make it sort fortnightly. Can this be done with fullcalendar? Solution: Just a heads ...

Handling CORS in Vue.js applications

As a newcomer to Vue, I am currently grappling with a CORS issue in my application. During development at http://localhost:8080/, sending a request to , I was able to resolve the CORS problem using the following code snippet: vue.config.js module.exports ...

Dealing with undefined Ajax values in PHP

Every time I call the function, I receive an undefined value and it's baffling me as to what could be causing this issue. You are logged in as undefined, Error undefined Ajax script: function Submit() { console.log('asd') $.ajax({ ...

Unlocking Google APIs Data through Service Account in JavaScript without User Approval

Is there a way to obtain an Access Token for Google APIs without requiring user consent, utilizing a Service Account in JavaScript? Alternatively, is it possible to retrieve the Access Token using an API Key, Client ID, and Client Secret? ...

Exploring the capabilities of VueJs in detecting events triggered by parent components

When users click on a specific image in the Collection(parent component), my goal is to display that image in a Modal(child component). Below is the code snippet: routes.js import Home from './components/Home'; import About from './compone ...

"The presence of the $_GET URL parameter following the execution of the pushstate

Running a WordPress website and facing the challenge of updating the URL server-side without reloading the page. On my homepage, there is a button triggered by this code: <button onclick="javascript:window.history.pushState('test','&apo ...

The focus is being lost on the ng-model when used within an ng-repeat

Within my JavaScript code, I am initiating a new question object like this: $scope.newQuestion = { answers: [] }; This is how it reflects in the HTML: <div class="row" ng-repeat="answer in newQuestion.answers"> <div class="input-field col m ...

I have noticed that when I close the Material-UI dialog, it prevents me from interacting with my

After closing the material-ui dialog box, I seem to be unable to click or touch anything on my page. The useState hook is used here: const [open, setOpen] = useState(false); This function is called when handling the dialog close action: const handleClose ...

Ensuring that EJS IF/ELSE statements are evaluated accurately

I am encountering an issue where my variable 'answer' is returning the string 'success' and displaying correctly in the view. However, the IF/ELSE statement always seems to evaluate to the ELSE condition and displays 'no' inst ...

retrieving attribute values from JSON objects using JavaScript

I am struggling to extract certain attribute values from a JSON output and use them as input for a function in JavaScript. I need assistance with this task! Below is the JSON data that I want to work with, specifically aiming to extract the filename valu ...

Should I increase the number of followers, or opt for an aggregated method to monitor them?

My system loads products using an infinite scroll, displaying 12 at a time. Sometimes, I may want to sort these products based on the number of followers they have. Here's how I keep track of the followers for each product: The follows are stored i ...

Examples of various spatial categories in the gun database, such as public space, user space, and frozen space

It appears that the Gun functionality is quite impressive - both practical and user-friendly! However, I am having trouble grasping the distinction between a public space put, a user space put, and a frozen space put. I've tried to illustrate this wit ...

Is it possible to automatically extract HTML code from a webpage using a function, without having to do it manually?

Is there a way to fetch the HTML code of a website after running a particular function? Here's the scenario I'm dealing with: I need to extract the link of a source embedded in an iFrame element that only becomes visible when I execute a specif ...