How should you correctly display the outcome of a mathematical function on a data property in a v-for loop in VueJS?

Recently, I've been developing a dice roller using Vue for a game project. The approach involves looping through different types of dice with v-for to create buttons and display the result in an associated div element. However, despite correct console logs, there seems to be an issue with updating the rollResult where it should be interpolated. For brevity, only the essential code has been shared here. If more details are needed, please don't hesitate to ask. Thank you in advance!

HTML:

<v-list-tile v-for="die in dice" :key="die.name">
...
 <template v-slot:activator="{ on }">
      <v-btn class="primary" @click="rollDice(die.sides)">Roll</v-btn> 
          <div>{{rollResult}}</div>
</template>
...
</v-list-tile>

Data:

      rollResult: 0,
      dice: [
        { sides: 4 },
        { sides: 6 },
        { sides: 8 },
        { sides: 10 },
        { sides: 12 },
        { sides: 20 }
      ],

Function:

    rollDice: function(n) {
     let rollResult = Math.ceil(Math.random() * n);
        console.log(rollResult);
    }

Answer №1

You have defined a local variable instead of mutating the state (the data). Here is the correct usage:

rollDice: function(n) {
    this.rollResult = Math.ceil(Math.random() * n);
    console.log(this.rollResult);
}

See it in action:

new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue.js!',
    rollResult: 0,
    dice: [
      { sides: 4 },
      { sides: 6 },
      { sides: 8 },
      { sides: 10 },
      { sides: 12 },
      { sides: 20 }
    ],
  },
  methods: {
    rollDice: function(n) {
        this.rollResult = Math.ceil(Math.random() * n);
        console.log(this.rollResult);
    }
  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <div v-for="die in dice" :key="die.name">
    <button class="primary" @click="rollDice(die.sides)">Roll {{ die.sides }}</button>
    <div>{{rollResult}}</div>
  </div>
</div>

If you require individual results, convert rollResult into an array (or an object) and be mindful of some considerations (such as using Vue.set()):

new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue.js!',
    rollResult: [0, 0, 0, 0, 0, 0],
    dice: [
      { sides: 4 },
      { sides: 6 },
      { sides: 8 },
      { sides: 10 },
      { sides: 12 },
      { sides: 20 }
    ],
  },
  methods: {
    rollDice: function(n, index) {
        Vue.set(this.rollResult, index, Math.ceil(Math.random() * n));
        console.log(this.rollResult);
    }
  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <div v-for="(die, index) in dice" :key="die.name">
    <button class="primary" @click="rollDice(die.sides, index)">Roll {{ die.sides }}</button>
    <div>{{rollResult[index]}}</div>
  </div>
</div>

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

Identifying the presence of node.js on your system

After installing node.js, I found myself at a loss on how to run applications. Despite the lack of instructions, I was determined to test if it was working by executing a script named hello.js: console.log('hello world'); I couldn't help b ...

Prevent Click Event in JQuery

I have a requirement to disable all click events on my webpage. However, even after using the appropriate code to prevent these events from firing, some of them are still getting called. Let me explain with an example. <div id='parent'> ...

Oops! It seems like there was an issue trying to access properties that are undefined while reading 'pipe' in Angular12

I encountered an issue when trying to send an AJAX request, displaying the following error message: ERROR TypeError: Cannot read properties of undefined (reading 'pipe') This error occurred in the ajax-loader.interceptor.ts class export class A ...

What could be the reason for Bootstrap not functioning on the homepage of my Laravel website?

My Laravel Journey As a newcomer to Laravel, I decided to dive in and learn by following tutorials on YouTube. The first step was uploading my project to a domain to test database connections using MySQL instead of SQLite as shown in the tutorial. Although ...

AngularJS directive error: Incorrect function invoked

I have two similar scenarios where I need to apply validators for specific files, even though I am aware that this goes against the DRY principle. However, being new to AngularJS, I am still learning the ropes. module.js var $moduleExample = angular.modu ...

Troubleshooting issues with AngularJS $watch not triggering properly

Even though Deep watch has been activated in the factory, it is not triggering. What steps can be taken to resolve this issue and ensure that an event is triggered when the 'name' value changes? Javascript Code: var app = angular.module('a ...

Add empty objects to an array using a push function following the Vue JS constructor function

During my learning journey with Vue JS, I encountered an issue while attempting to populate an array with objects using a constructor function and the push method. Surprisingly, in Vue JS, the push function inserts a blank object into the array instead of ...

What is the best way to achieve this in Node.js/Express using Redis? Essentially, it involves saving a callback value to a variable

Here is the data structure I have set up in redis. I am looking to retrieve all values from the list and their corresponding information from other sets. Data structure : lpush mylist test1 lpush mylist test2 lpush mylist test3 set test1 "test1 value1" ...

Personalize or adjust the PrimeVue Bootstrap theme SCSS/SASS to fit your needs

As a newcomer to PrimeVue, I am eager to learn how to customize and modify the Bootstrap theme. In another project, I successfully revamped the variables of Bootstrap (v4) and now wish to incorporate them into PrimeVue. My preference is to use SCSS for bet ...

Struggling with organizing my code in node.js - it's all over the place and not very reliable. How should I tackle this

Can anyone help me troubleshoot an issue I'm facing with code that writes to the console late or in random order? var request = require('request'); var vFind = 'HelloWorld'; var vFound = false; var vSites = ['http://www.youtu ...

Tips for eliminating unnecessary data in written content

Could anyone provide a recommended method for removing unnecessary symbols from text strings? For instance, transforming "CWC%20-%20Maint%20Eng%20-%20El" into the more readable format of "CWC - Maint Eng - El". ...

Packages have gone astray post node_modules scrub

I encountered an issue with npm run watch getting stuck at 10%, so I took the step of deleting the node_modules directory and package-lock.json. However, it seems that I may have installed modules using npm install without the --save-dev option. Even after ...

In what way are these columns altering their layout without the use of JavaScript?

While I was searching for a solution to organize content based on screen size, I came across this website. The layout of the site changes depending on the size of the browser window. When I resize my browser or view the site on a phone, the large image at ...

Is it feasible to invert the order of arguments in async.apply?

According to the async documentation: apply(function, arguments..) Creates a function continuation with certain arguments already applied. This can be useful when combined with other control flow functions. Any additional arguments passed to the returned ...

What steps are involved in a server utilizing Next.js to create a complete document for transmission to the client?

Understanding Next.js has been quite challenging for me. I am struggling to grasp how it operates on the server and how the server is able to implement server side rendering with the files generated by Next.js during the build process. I have a good under ...

unable to retrieve JSON sub-elements

I encountered an issue while attempting to iterate through the JSON object provided. When trying to access the content-items using page.content-items, I received an error message. Is it possible to access an object that has a key with "-" in its name? Co ...

What is the correct way to define an abstract method within a class to ensure that an IDE detects and notifies if the abstract method is not implemented

Is there a way to properly define an abstract method in an abstract class and have the IDE notify us if we forget to implement it? I attempted the following approach, but it did not work: export abstract class MyAbstractClass { /** * @abstract ...

Which symbol is preferable to use in JS imports for Vue.js/Nuxt.js - the @ symbol or the ~ symbol?

I am seeking guidance on a matter that I have not been able to find a clear answer to. Webapck typically uses the ~ symbol as an alias for the root directory. However, I have noticed that some developers use the @ symbol when importing modules using ES6 s ...

Caution: The Vue Class Based Component is signalling that a property is not defined on the instance, yet it is being

I've been experimenting with creating a Vue component using vue-class-component and TypeScript. I referenced the official documentation here: https://github.com/vuejs/vue-class-component. Despite defining the data within the class as shown below, I en ...

Retrieve the id of the anchor tag that was selected upon clicking, and then dynamically change the content of another div

Seeking guidance on how to dynamically change the content of a div element based on which anchor tag is clicked. Below is the HTML structure and JavaScript function I have attempted: HTML: <div> <a id="a1" href="javascript: changeDiv();">tag1 ...