Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

uuid for v-for key with vue-uuid?

I'm trying to use a random string (UUID v4) with vue-uuid for current items and items added to the list in the future (this is a to-do list type app) but I'm not sure what to correct syntax is.

I installed it and added it to my project in main.js:

import UUID from 'vue-uuid';
Vue.use(UUID);

However, I don't know how to use it in my Vue component. This is what I tried:

Template:

<transition-group
  name="list"
  enter-active-class="animated bounceInUp"
  leave-active-class="animated bounceOutDown"
>
  <li v-for="item in skills" :key="uuid">{{ item.skill }}</li>
</transition-group>

Script:

import { uuid } from 'vue-uuid';

export default {
  name: 'Skills',
  data() {
    return {
      uuid: uuid.v4(),
      skill: '',
      skills: [{ skill: 'Vue.js' }, { skill: 'React' }]
    };
  },
};

For :key="uuid", I get an error saying Expected 'v-bind:key' directive to use the variables which are defined by the 'v-for' directive (vue/valid-v-for). I also tried changing it to :key="item.uuid" which makes that error go away, but then the list doesn't appear.

project repo (based on this Udemy Vue crash course)

like image 905
nCardot Avatar asked Jan 18 '20 02:01

nCardot


1 Answers

Try this:

<template>
  <div id="app">
    <p :key="item.uuid" v-for="item in skills">{{ item.skill }}</p>
  </div>
</template>

<script>
import { uuid } from "vue-uuid";

export default {
  name: "App",
  data() {
    return {
      skills: [
        { uuid: uuid.v4(), skill: "Vue.js" },
        { uuid: uuid.v4(), skill: "React" }
      ]
    };
  }
};
</script>

This is a working demo: https://codesandbox.io/s/nifty-sutherland-b0k9q

UPDATED

to be dynamic

There are two moments that you could add the uuid to each element in the skills array:

1 When adding a new skill:

addSkill() {
  this.$validator.validateAll().then(result => {
    if (result) {
      this.skills.push({ uuid: uuid.v4(), skill: this.skill });
      this.skill = "";
    }
  });
}

2 When rendering them, in this case, you might use a computed property like so:

import { uuid } from 'vue-uuid';

export default {
  name: 'Skills',
  data () {
    return {
      skill: '',
      skills: [{ skill: 'Vue.js' }, { skill: 'React' }]
    };
  },
  computed: {
    computedSkills () {
      return this.skills.map(skill => {...skill, uuid: uuid.v4() })
    }
  }
};

And then using the computedSkills computed property for rendering rather than the skills property. Something like:

<li v-for="item in computedSkills" :key="item.uuid">{{ item.skill }}</li>
like image 69
You Nguyen Avatar answered Nov 18 '22 09:11

You Nguyen