I am using Vue.js to generate divs and I would like to use data from a JSON file to do so.
It doesn't necessarily have to be from the JSON but that would be preferable, I just need to create a unique id for each instance of the div in the html below.
What is the best way to create unique ID's for each of the divs?
HTML
<ul>
<li v-for="(member, index) in cyclists" :key="index" class="col-md-4 inview fromBottomIn" data-in="fromBottomIn" data-out="fromBottomOut">
<div class="cycling__card">
<div class="cycling__rider-container">
<span class="cyclist__name">{{member.name}}</span>
</div>
<!-- Need to add id's to the div below -->
<div id={{member.name}}>
</div>
</div>
</li>
</ul>
JSON
"cyclists": [
{
"name": "Jason",
"position": "CEO",
},
{
"name": "Mike",
"position": "Digital Strategist",
},
{
"name": "Tom",
"position": "Vice President, Product Management",
},
{
"name": "Jeff",
"position": "Senior Director, Creative",
},
}
I'm in this case using uuid, you will need to merge json data to another object wit new id, so the example:
<script>
import { uuid } from 'vue-uuid';
export default {
data() {
return {
uuid: uuid.v1(),
id: null
}
},
computed: {
newCyclists: function () {
const id = this.id;
const newID = this.$uuid.v4();
return {
...cyclists,
id: newID,
}
}
}
};
</script>
in computed
using spread operator to merge new ID with current JSON data with a new ID, vue-uuid
come from uuid library and v4 is related to generate ID's
There are different approaches.
Generate a uuid for each one on the fly. You can use this amazing function for uuid version 4 developed by the community to be the shortest possible:
function b(a){return a?(a^Math.random()*16>>a/4).toString(16):([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,b)}
If you didn't want to load in an additional module like vue-uuid
you could use this function to generate a hash of the result of stringifying each array object on the assumption that each name/position will be unique.
I've used this Stackoverflow answer as the basis of this one.
const data = [{"name":"Jason","position":"CEO"},{"name":"Mike","position":"Digital Strategist"},{"name":"Tom","position":"Vice President, Product Management"},{"name":"Jeff","position":"Senior Director, Creative"}];
function genHash(str) {
var hash = 0, i, chr;
if (str.length === 0) return hash;
for (i = 0; i < str.length; i++) {
chr = str.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0;
}
return hash;
};
// For each object in the array create
// a stringyfied version of it and create
// a hash
data.forEach(obj => {
obj.id = genHash(JSON.stringify(obj));
});
console.log(data);
Then you can loop over the data as you would normally.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With