VuesJS, generate randomkey in v-for loop - vue.js

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

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>

There is a simpler, more concise technique shown below. It avoids polluting the iterated object with a redundant property. It can be used when there is no unique property in the objects you iterate over.
First in your viewmodel add the method to generate a random number (e.g. with Lodash random)
var random = require('lodash.random');
methods: {
random() {
return random(1000);
}
}
Then in your template reveal the index in v-for and randomize it in v-bind:key with your random() method from the viewmodel by concatenation.
<div v-for="(task, index) in tasks" v-bind:key="index + random()">
// Some markup
</div>
This is as clean as easy.
However note this approach would force redrawing each item in the list instead of replacing only items that differ. This will reset previously drawn state (if any) for unchanged items.

I do like this
function randomKey() {
return (new Date()).getTime() + Math.floor(Math.random() * 10000).toString()
}

Related

Comparing with previous iteration in v-for

Here's my code:
<div v-for="(message) in messages">
<div class="message-divider sticky-top pb-2" data-label="Test"> </div>
...
What I need to achieve is, if current iteration's message.createdAt.seconds differs by day from the previous one to show message-divider element.
So the time format is in seconds like this: 1621515321
How can I achieve this?
You can do variable assignment as part of the template, so you could assign the previous value and compare, but this is not a very good idea. Instead you can use a computed to prepare your array to only have the objects you want, with the data you need. So in this case, you could use a computed to create a new array with objects that have additional flags like className or showDivider etc.
example:
computed:{
messagesClean(){
let lastCreatedAt;
return this.messages.map(message => {
const ret = {
...message,
showDivider: lastCreatedAt + 3600*24 < message.createdAt.seconds // your custom logic here
}
lastCreatedAt = message.createdAt.seconds
return ret
}
}
}
the logic to determine when the divider gets shown is up to you there, I suspect it may be a bit more complicated than differing by a day.
You need something like this:
<div v-if="compEqRef">
OK
</div>
<div v-else >!!OK!!</div>
Here compEqRef could be in computed:
computed: {
compEqRef() {
//do something
}
},

Looping in Vue and adding dynamic className

I am quite new to Vue and I have an issue.
I have an array of objects and I want the wrapper of the loop to have dynamic className
For example
<div v-for="({time, date, name}, i) in myObject" :key="i" class="my-custom-class">
well, if the key (i) is greater than 3 then I want the className to have a different name
or at least to add an extra name (like hiddenDiv).
I know is not possible to add the v-if condition in the v-for statement.
Any help is appreciated.
You could bind the class using a condition based on the current loop index :class="{'hide-div':i>3}":
<div v-for="({time, date, name}, i) in myObject"
:key="i" :class="{'hide-div':i>3}" class="my-custom-class" >
Another way of doing this using computed property...
<div v-for="({time, date, name}, i) in myObject"
:key="i" :class="getClassName(i)" class="my-custom-class" >
and in your computed
computed: {
getClassName() {
return i => {
if(i === 0) return 'classOne';
elseif(i === 1) return 'classTwo'
else return 'classThree';
// In this way you can maintain as many classNames you want based on the condition
}
}
}
If you want to apply a dynamic class in vue then you can use class bindings to apply a specific class to the element.
You can read about class and style bindings here.
Also, you can define a method with the class and apply some conditions on which the class needs to be changed.

List of components not updating

I have this template displaying a list of components:
<template>
<v-container id="container">
<RaceItem v-for="(item, index) in items" :key="item + index" />
(...)
When the array "items" is updated (shift() or push() a new item), the list displayed is not updated.
I'm sure I'm missing something on how Vue works... but could anyone explain what's wrong?
The key attribute expects number | string | boolean | symbol. It is recommended to use primitives as keys.
The simplest usage is to use a primitive unique property of each element to track them:
<RaceItem v-for="item in items" :key="item.id" />
... assuming your items have unique ids.
If you use the index as key, every time you update the array you'll have to replace it with an updated version of itself (i.e: this.items = [...items]; - where items contains the mutation).
Here's how your methods would have to look in that case:
methods: {
applyChangeToItem(item, change) {
// apply change to item and return the modified item
},
updateItem(index, change) {
this.$set(
this.items,
index,
this.applyChangeToItem(this.items[index], change)
);
},
addItem(item) {
this.items = [...this.items, item];
},
removeItem(index) {
this.items = [...this.items.filter((_, i) => index !== i)];
}
}
Can you try something like this
Put componentKey on v-container and use forceRender() after your push is done

Creating div in vue for loop

I'd like to do v-for loop for creating a div. I'm doing a minesweeper game and here is my code :
<div class="grid">
<div class="square"
v-for="(square, index) in squares"
:id="index"
:key="index"
:class="squares[index]"
#click="clicked(square, index)"
>
</div>
</div>
'Squares' in this code is an array with shuffled classes 'bomb' or 'empty'. I know that it's wrong because after I click on random square I get only this class from te 'squares' array. What should be there instead of this 'squares' array in v-for. I want to get whole with classes, attributes etc. because later I have to use 'classList' 'contains' etc.
Sorry, maybe I'm completly wrong and talking bullshit, but I started with vue 3 weeks ago.
Here is the method clicked which I want to use
clicked(square) {
if(this.isGameOver) return;
if(square.classList.contains('chechked') || square.classList.contains('flag')) return
if(square.classList.contains('bomb')) {
this.gameOver(square);
} else {
let total = square.getAttribute('data');
if(total != 0) {
square.classList.add('checked');
square.innerHTML = total;
return
}
}
square.classList.add('checked');
}
You want to access the div element but you are passing the object in the method and you are asking for classList into the object (that does not have it). You should query the element instead.
Change the #click handler in your component to:
#click="clicked"
and your method to:
clicked(event) {
let square = event.target;
console.log(square);
console.log(square.classList);
...

For each results in v-for loop how can I nest another v-for loop using a parameter from the results of the first loop

Using a v-for loop in Vue js. I am looping through the readingTasks data object which correctly produces two results from the data below.
readingTasks:Array[2]
0:Object
enabled:true
newunit:-1
task:"The part 3 guide"
unit:-1
unit_task_id:27
url:"#"
1:Object
enabled:true
newunit:-1
task:"The part 3 training units"
unit:-1
unit_task_id:28
url:"#"
The bit I am unsure about is how for each result, how do I run another Axios database call that shows if the reading Task is complete or not. For example for the first record, the complete status should be true (unit_task_id:27) and the second record should be false.
userTasks:Array[1]
0:Object
complete:true
enabled:true
newunit:-1
task:"The part 3 guide"
unit:-1
unit_task_id:27
unit_task_user_id:21
<ul>
<li v-for="task in readingTasks">
{{task.task}}
//trying to call a function that does an Axios call passing in parameters from readingTasks
{{getUserTaskByUnit(task.unit, task.unit_task_id)}}
<template v-for="usertask in userTasks">
{{usertask.complete}}
</template>
</li>
</ul>
//javascript if its useful
data: {
readingTasks: [],
userTasks: []
},
mounted() {
this.lastUnit();
},
methods: {
//functons
lastUnit: function() {
this.tasks();
},
tasks: function() {
var self = this;
var unit = this.unit;
axios.get("/WebService/units.asmx/GetTasks?unit=" + unit).then(function(response) {
self.readingTasks = response.data;
})
.catch(function(error) {
console.log(error);
})
.then(function() {
});
},
getUserTaskByUnit: function(unit, unitTaskId) {
var self = this;
axios.get("/WebService/units.asmx/GetUserTasks?unit=" + unit + "&unitTaskId=" + unitTaskId).then(function(response) {
self.userTasks = response.data;
})
.catch(function(error) {
console.log(error);
})
.then(function() {});
}
This code seems close to doing the correct thing, however {{usertask.complete}} flickers between true and false for both sets of results. Like it is stuck in a loop.
I would expect the first result to show True here and the second result to show False.
The part 3 guide - true
The part 3 training units - false
There are a few problems here.
The template has a dependency on userTasks, so every time userTasks changes it will cause the component to re-render, running the template again.
Every time the template runs it calls getUserTaskByUnit for both tasks. That will, asynchronously, update userTasks. When userTasks is updated it will trigger a re-render, which will call getUserTaskByUnit again, going round and round in an infinite loop.
Worse than just being an infinite loop, each time it renders it will trigger two requests, each of which will trigger another re-rendering. The number of requests will balloon exponentially.
When those requests do return you're then storing them in userTasks. But both responses are being stored in exactly the same place, so you'll only ever see the results of one request in the UI.
The first thing you'll need is a better data structure for storing the responses in getUserTaskByUnit. The simplest place to store them would be on the tasks in readingTask. That might look something like this:
// Note the whole task is now being passed to getUserTaskByUnit
getUserTaskByUnit: function(task) {
var self = this;
axios.get("/WebService/units.asmx/GetUserTasks?unit=" + task.unit + "&unitTaskId=" + task.unit_task_id).then(function(response) {
task.userTasks = response.data;
})
...
}
The call to getUserTaskByUnit needs moving out of the template. Moving it into the tasks method seems as good a place as any. There are also a few changes required to get it to work with the new version of getUserTaskByUnit:
tasks: function() {
var self = this;
var unit = this.unit;
axios.get("/WebService/units.asmx/GetTasks?unit=" + unit).then(function(response) {
var readingTasks = response.data;
// Pre-populate userTasks so it will be reactive
readingTasks.forEach(function(task) {
task.userTasks = [];
});
// This must come after userTasks is pre-populated
self.readingTasks = readingTasks;
readingTasks.forEach(function(task) {
// Passing task to getUserTaskByUnit, not unit and unit_task_id
self.getUserTaskByUnit(task);
});
})
...
Then within the template we'd need to loop over task.userTasks:
<ul>
<li v-for="task in readingTasks">
{{task.task}}
<template v-for="usertask in task.userTasks">
{{usertask.complete}}
</template>
</li>
</ul>
There are alternative data structures we could use depending on what other requirements you have. For example, you could retain a separate userTasks object to hold the userTasks but for that to work it would need to be a nested data structure rather than just an array. You'd need to key it by unit and then unitTaskId. The result in the template would be something like this:
<ul>
<li v-for="task in readingTasks">
{{task.task}}
<template v-for="usertask in userTasks[task.unit][task.unit_task_id]">
{{usertask.complete}}
</template>
</li>
</ul>
Much like with the earlier solution you would need to pre-populate the userTasks with empty values when readingTasks first loads to ensure the values are reactive and also to avoid the template blowing up at the undefined entries. Alternatively you could use $set and suitable v-if checks respectively.
This is all quite fiddly. It may be that you can simplify it a little based on your knowledge of the system. For example, it may be possible to form compound string keys for userTasks rather than using two levels of nesting. Or it might be that unit is a prop that can be considered constant and doesn't need including in that data structure.
Your userTasks is a view property and gets overwritten upon every call to getUserTaskByUnit (i.e. for each item in readingTasks). What you instead want is a nested structure. You should call getUserTaskByUnit in a loop as soon as readingTasks got loaded, i.e. after the line self.readingTasks = response.data;, and store the response as a property for every readingTask object.