Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VuesJS, generate randomkey in v-for loop

Tags:

vue.js

vuejs2

Good evening,

My problem is this: I have a loop that displays simple divs. I have a method that specifies the dimensiosn of my div (mandatory in my case). However, when I call the method a second time by changing the sizes of the divs, it does not work because there is no re-render.

To overcome this, I generate a guid on my: key of v-for with a variable such as:

<div v-for="task in tasks" :key="task.id + guid()">...blabla...</div>

Is it possible to generate this code directly during the loop to avoid concatenation?

<div v-for="(task, maVar=guid())  in tasks" :key="maVar">...blabla...</div>

PS : code for guid() method :

guid() {
   return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
      (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16))
}

Thanks

like image 302
Brice Chaponneau Avatar asked Feb 01 '18 19:02

Brice Chaponneau


1 Answers

You could create a computed property that returns an array of task with a guid added, or if you want to leave tasks untouched, return an object containing each task plus a guid,

computed: {
  tasksWithGuid: function() {
    return this.tasks.map(task => { return {task, key: task.id + guid() } })
  }
}
<div v-for="taskWithGuid in tasksWithGuid" :key="taskWithGuid.key">
  {{taskWithGuid.task.someProperty}}
</div>
like image 73
Richard Matsen Avatar answered Nov 15 '22 12:11

Richard Matsen