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

What is the best way to execute a JavaScript function using Python Selenium?

Is it possible to repeatedly call the MapITRFtoWgs84() function with input from a text file and save the output to another text file? I believe Selenium might be the right tool for this task. Could you provide guidance on how to achieve this? Attached is ...

Using jQuery .sortable() to reorder list items and update their IDs based on their new positions

My apologies for my limited English skills, but here is what I am trying to achieve. I have a list structured like this: <ul id="sortable" class="sortable"> <li id="1">1</li> <li id="2">2</li> <li id="3">3</li> &l ...

The $resources headers have not been updated

My objective is to include a header with each HTTP request for an ngResource (specifically, an auth token). This solution somewhat accomplishes that: app.factory('User', ['$resource','$window', function($resource,$window,l ...

Different ways to modify the CSS file of the bx-slider plugin for multiple sliders within a single webpage

Currently in the process of building a website using bx slider. I am looking to incorporate three sliders onto a single page for sliding HTML content. Initially, I added a bx slider to the page and customized it using CSS. I made modifications within jqu ...

Potential issue with Jhipster: loading of data could be experiencing delays

I've encountered an issue with getting my chart to display properly. I am working on creating a chart using ng2-charts, where I retrieve data from a service and then display it on the chart. The problem arises when the data is not correctly displayed ...

Can webpack or React be set up to automatically import files, eliminating the need to manually use the `import` statement each time?

On a regular basis, I find myself typing: <div style={{display:'flex'}}> ... </div> But it would be more convenient to simply use: <Row> ... </Row> However, I don't want to have to import Row from './Row&ap ...

Sending arrays in JSON format using Node.js Express (res.json)

I have a code snippet like this: app.get('/orders/:pizzeriaID/:status', async (req, res) => { try { const requestedOrderByPizzeriaID = req.params['pizzeriaID']; const requestedOrderByStatus = req.params['status']; ...

Combining relationships from various models in Laravel to streamline queries

Is it possible to combine two relationships into a single query from two separate models? class User extends Authenticatable { public function relazioneFollower() { return $this->belongsToMany(User::class, 'user_follower','follower ...

Ways to troubleshoot the "TypeError: Cannot read property 'value' of null" issue in a ReactJS function

I keep encountering a TypeError: Cannot read property 'value' of null for this function and I'm struggling to pinpoint the source of the issue. Can someone help me figure out how to resolve this problem? By the way, this code is written in R ...

tips for formatting code to prevent warnings in Vue

Currently tackling my inaugural Vue project at the workplace, I've encountered warnings that need to be resolved by utilizing --fix. These warnings mainly pertain to indentation, spacing, new lines, and similar issues. Is there a specific formatter de ...

Can you list out the directives that are responsible for generating child scopes in AngularJS?

I recently discovered that when using ng-if, it actually creates a child scope, leading to some confusion on my end. I'm curious about the reasons or benefits behind ng-if's scope creation. Can you also tell me which other built-in directives cre ...

How can I use regular expressions to locate a React JSX element that contains a specific attribute?

Currently conducting an audit within a vast codebase, my task involves searching for all instances of a component where it is utilized with a specific prop. I believe that using regex could prove beneficial in this situation; however, the challenge lies in ...

A comprehensive guide on implementing filtering in AngularJS arrays

I am working with the array provided below: [ { Id: 1, Name: "AI", Capacity: 2, From: "2021-10-27T08:00:00", To: "2021-10-27T08:50:00", }, { Id: 2, Name: "TEST", Capacity: 2, ...

Send form based on the outcome of the ajax request

I have developed a form that triggers an ajax request upon submission to check the validity of the data. My goal is to automatically submit the form if the ajax response confirms the data is valid, and prevent the form submission if the data is invalid. $ ...

Pagination with composite queries in Firestore allows for efficient retrieval of

Currently I am attempting to paginate a composite index query, let size = data.length let lastElement = data[size-1].commentCount db.collection('user-content').orderBy('commentCount','desc').orderBy('likes', 'd ...

How to enable Autocomplete popper to expand beyond the menu boundaries in Material UI

Within my Menu component, I have an Autocomplete element. When the Autocomplete is clicked, the dropdown list/Popper appears but it's confined within the Menu parent. How can I make it so that the Autocomplete's dropdown list/Popper isn't re ...

Concerning the issue of components not loading correctly when using Angular with Lazy Loading Routing

Encountering an unusual issue while utilizing lazyload routing in our application! Within AppModule, there is TopModule followed by DashboardModule, all being loaded lazily. When localhost:4200/dashboard is accessed, the loading sequence is AppModule, To ...

Encountering difficulties in populating mongoose document following a model query

Hi everyone, this is my first time posting on SO so I'm hoping for some positive outcomes. I've been using Mongoose in a current project without any issues until now. The problem arises when trying to populate object references after querying fo ...

Tips for implementing owl carousel in Nuxt.REACT_UNITS_CODIFY

Is there a way to make the script function on every page without the need for these pages to be reloaded? I have the Owl Carousel script in my static folder, and I have already included it in nuxt.config.js as shown below: head: { title: 'title&ap ...

Issue with jQuery UI: Accordion not functioning properly

I have created a nested sortable accordion, but there seems to be an issue. Within the 'accordion2' id, the heights of each item are too small and a vertical scroll bar appears. The content of the item labeled '1' is being cut off, show ...