Tips for refreshing a template with a click event

Problem Statement

I currently have a piece of code that involves updating the results-box with a randomly chosen selection. I need to know how to modify the template when a @click event occurs.

<template>
  <div class="container">
    <button @click="getDecision()" class="ui primary button">Discover</button>
    <p id="results-box"></p>
  </div>
</template>

<script>
  export default {
    name: "SlapButton",
    data() {
      return {

      }
    },
    methods: {
      getDecision: function () {
        var decisions = [
          "choice 1",
          "choice 2",
          "choice 3",
          "choice 4",
          "choice 5",
          "choice 6"
        ]
        var randNum = Math.floor((Math.random() * decisions.length) + 0);
        var randChoice = decisions[randNum];
      }
    }
  }

</script>

Question

Following a click event on the button, getDecision() function is activated, and a random choice is selected from the decisions array. How do I present this random choice randChoice within the p tag #results-box.

Answer №1

Here is a code snippet to help you generate random choices when a button is clicked:

<template>
  <div class="container">
    <button @click="pickRandomChoice" class="ui primary button">Choose</button>
    <p id="results-box">
      {{selectedChoice}}
    </p>
  </div>
</template>

<script>
export default {
  name: "RandomChoiceGenerator",
  data() {
    return {
      selectedChoice: '',
      choices: [
        "Option 1",
        "Option 2",
        "Option 3",
        "Option 4",
        "Option 5",
        "Option 6"
      ]
    }
  },
  methods: {
    pickRandomChoice() {
      var randomIndex = Math.floor(Math.random() * this.choices.length);
      this.selectedChoice = this.choices[randomIndex];
    }
  }
}
</script>

Answer №2

To demonstrate how this works, check out this example and take a look at another mini demonstration

In essence, all you need is a variable to store the randChoice. Once you define this variable within the data (){} object, set its value within your method like so:

export default {
  name: "SlapButton",
  data() {
    return {
      randomChoice: false
    }
  },
  methods: {
    getDecision: function () {
      var decisions = [
        "choice 1",
        "choice 2",
        "choice 3",
        "choice 4",
        "choice 5",
        "choice 6"
      ]
      var randNum = Math.floor((Math.random() * decisions.length) + 0);
      this.randomChoice = decisions[randNum];
    }
  }
}

Then, display this data in your element like this:

<p id="results-box"> {{randomChoice}} </p>

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

Combining multiple arrays in Node.js to create a single JSON file

I'm exploring the world of nodejs and currently working on creating a Json parser that will pull data from a Json API, allow me to access specific data points (some of which will need transforming), and then save it to a Json file. I recently came ac ...

What triggers the invocation of the onerror handler in XMLHttpRequest?

I am facing a bit of confusion when trying to understand the functionality of XMLHttpRequest's handlers. After reading the specification regarding the onerror handler, it mentions: error [Dispatched ... ] When the request has failed. load [Dispa ...

The webpage is not displaying any results despite using .innerHTML with Ajax

I am currently developing a web application that displays query results using the Google Books API. While my code is functioning, I am encountering an issue where the .innerHTML method does not show any results on the HTML page. Below is the HTML code bein ...

Why does Vue only change a specific array element without updating the DOM?

My curiosity is piqued by a puzzling issue with updating specific items in an array using Vue.js. The documentation cautions that: Due to limitations in JavaScript, Vue cannot detect the following changes to an array: When you directly set an item with th ...

Build an upvote feature using PHP and WordPress that allows users to vote without causing a page reload

Just starting out as a developer and currently working on a website using WordPress. I want to implement an upvote button that allows users to upvote a post without the page needing to refresh. I understand that I'll need to use JavaScript to highligh ...

Implementing dynamic title insertion into a popover element using jQuery

My goal is to assign a title to my popover object in a local project. I have already included the following files: bootstrap.css v4.2.1 jquery.min.js v2.2.0 bootstrap.min.js v4.2.1 popper.min.js v1.11.0 Initially, there was a basic button present. <i ...

Having trouble getting req.files to work in a Node.js Express application?

Hello there, I'm facing an issue with accepting an uploaded file. Every time I call req.files, it comes out as undefined. I can't seem to figure out what I am doing wrong... Below is a snippet of my app.js file: var express = require('expr ...

Steps for retrieving a Unicode string from PHP using AJAX

In order to retrieve Unicode strings from PHP for my project, I figured that using AJAX would be the most suitable method. $.ajax({ url: './php_page.php', data: 'action=get_sum_of_records&code='+code, ...

Tips for transforming this jquery script into "vanilla" javascript

Looking for assistance in translating this jQuery code into vanilla JavaScript (without the need for the jQuery library). var myConsole={ panel:document.querySelector('#something'), log:function(message){ this.panel.innerHTML+= m ...

Switch on and off the active class in child components using VueJS

I'm currently working on an explore page in VueJS that includes child components called toggle-tiles, which are displayed as grids. The goal is to apply an active class when a "toggle-tile" is clicked, but only one can be active at a time. Right now, ...

Refreshing a single HTML element in ASP.NET MVC - the simple way!

Recently, I put together an image gallery using the unite gallery jquery plugin and now I want to change up the images it displays. My plan is to have a button labeled "art" that, when clicked, triggers a function to update the directory path and load ne ...

Dealing with an empty req.body in an Express.js POST request

Having trouble solving this issue with a simple search. Can anyone provide clearer guidance? In the client-side code, I attempted to attach an object using xhr.send(obj). Currently, I'm trying to append to the formData object, but the result remains ...

Developing a Chessboard Using JavaScript

Seeking help with a Javascript chessboard project. I have successfully created the board itself, but facing difficulty assigning appropriate classes (black or white) to each square. Managed to assign classes for the first row, struggling with the remainin ...

Is it Possible to Achieve Callbacks From AJAX to PHP Despite the Inability to Serialize Closures?

Question How can I incorporate a PHP callback passed via AJAX, where the callback is executed by the page requested through AJAX? The Scenario Comments are submitted through AJAX with parameters serialized and encrypted for security. The issue arises wh ...

Unlocking $refs with the Composition API in Vue3 - A step-by-step guide

I am currently exploring how to access $refs in Vue 3 using the Composition API. In my template, I have two child components and I specifically need to obtain a reference to one of them: <template> <comp-foo /> <comp-bar ref="ta ...

Is webpack necessary for segregating dependencies during installation?

Currently, I'm diving into a tutorial on webpack and it's been three days already, but confusion still reigns! I am delving into the commands: npm i webpack --save-dev I find myself puzzled by the '--save-dev' in the above command whi ...

Creating pages or tabs within a table using HTML5 and Angular is a simple and effective way to organize

I have a REST response that returns around 500 records. These records are being displayed in an Angular table. I would like to add customization options for the user, allowing them to choose to display 10/20/30... records per page. Additionally, I want to ...

The matter concerning the intricacies of Rails, JQuery, Prototype, and RJS

I am exploring the integration of Jquery and ajax in rails 3.0.7, but I'm unclear on the current landscape regarding their usage together. There seems to be an abundance of hacks, plugins, and scripts available for utilizing JQuery. So: Is there an ...

Client.on facing issue with receiving data upon initial connection

Currently, I am utilizing the net module in order to establish a connection between my client and server. Below is the code snippet: const Net = require('net'); client = Net.connect(parseInt(port), host, function() { co ...

Within Blade, Laravel and Vue components are able to communicate by sharing data from one component to another

Is it possible to achieve this task? Here is the scenario: I have a left navbar displaying membership status (active/inactive). Once the payment gateway receives the payment, a webhook is triggered via Paddle(Laravel Paddle API). During the webhook proc ...