Is it possible to generate unique identifiers for v-for keys using vue-uuid?

I'm attempting to utilize a random string (UUID v4) using vue-uuid for existing items and future additions to the list in my to-do list style application. However, I'm uncertain about the correct syntax to use.

After installation, I included it in my project's main.js file:

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

Despite this, I am unsure of how to implement it within my Vue component. Here is what I have attempted:

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' }]
    };
  },
};

When using the :key="uuid", an error arises stating

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 resolves the error but causes the list not to display.

project repository (built upon this Udemy Vue crash course)

Answer №1

Give this a try:

<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>

Check out this working example: https://codesandbox.io/s/nifty-sutherland-b0k9q

UPDATE

to make it dynamic

You can add the unique uuid to each element in the skills array at two different points:

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, you can use a computed property like this:

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() })
    }
  }
};

Then, utilize the computedSkills computed property for rendering instead of the skills property. For example:

<li v-for="item in computedSkills" :key="item.uuid">{{ item.skill }}</li>

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

Chrome extensions using Cross-Origin XMLHttpRequest

Chrome extensions API states that cross-origin calls using the XMLHttpRequest object should be allowed with proper permissions: An extension can communicate with remote servers beyond its origin by requesting cross-origin permissions. Following the Goog ...

Converting XML to JSON using UTF-8 Encoding

I am currently working with xml2js to convert an XML feed into JSON format. However, I'm facing an issue where certain characters like Æ, Ø & Å are displayed as expected in the XML but appear differently after parsing. After parsing, I receive ...

What are the steps for utilizing CSS Global Variables?

Hey there, thank you for taking the time to help me out. I'm having a simple doubt that I just can't seem to figure out. So... here's my '/pages/_app.js' file: import '../public/styles/global.css'; export default funct ...

Is it advisable to employ jQuery(this) in this specific scenario?

My PHP script generates HTML a:link divs with different $linkname and $pageid values. It also creates corresponding jQuery scripts for each link: $output = '<a class="sig_lightbox_link" id="' . $pageid . '">' . ...

The minification of HTML scripts may cause problems with the <script> tag

Greetings! I have a PHP script that is used to minify the page by removing any comments or spaces. Here is the script: <?php function sanitize_output($buffer) { $search = array( '/\>[^\S ]+/s', '/[^&b ...

Is there a way to adjust this angular2 service to make it slightly more synchronous?

My goal is to create an Angular2 service that performs the following tasks: FTP to a remote server Read certain lines from a file Create a 'results' JSON object and return it to the component that called the service I have successfully impleme ...

Effortlessly move and place items across different browser windows or tabs

Created a code snippet for enabling drag and drop functionality of elements within the same window, which is working smoothly. var currentDragElement = null; var draggableElements = document.querySelectorAll('[draggable="true"]'); [].forEach ...

Interactive Component overlying Layer - HTML/CSS

Currently, I am working on a web application that features a navigation bar at the bottom of the screen. To enhance visibility, I decided to apply a linear gradient overlay above the underlying elements. This screenshot illustrates what I mean. However, I ...

I'm looking to create an array of tags that contain various intersecting values within objectArray

Initially const array = [ { group: '1', tag: ['sins'] }, { group: '1', tag: ['sun'] }, { group: '2', tag: ['red'] }, { group: '2', tag: ['blue'] }, { grou ...

Adding a jPlayer on the fly

I've been working on a code snippet to dynamically add jPlayers through a function. Here is the code I have so far: function audio_player(audio, title, type) { var id = $('.audio').length; $('#audio').append('<di ...

The es6 object class is not defined

Hey there, I'm currently working on a simple pong game and encountering an issue with passing the player object into drawPlate. It seems to be printing the information correctly, but then I get hit with an Uncaught TypeError exception. The data print ...

Tips for sequentially arranging and rearranging an array of numbers, even when duplicates are present

Encountered a perplexing issue that has me scratching my head in an attempt to visualize a solution. Currently, I am working with an array of objects that appears as follows: let approvers = [{order:1, dueDate: someDate},{order:2, dueDate: someDate}, ...

Dynamically showcasing content in an HTML table

Having trouble with this code snippet. It's supposed to iterate through array objects and display them in an HTML table. The third row should have buttons, but nothing is showing up. Can you spot the issue? Here's the HTML code: <html> & ...

React Native package identifies a primary module for handling HTTPS requests

For my latest project, I decided to experiment with incorporating HTTPS. I began by creating a new project using expo init test and then installed the HTTPS library with npm install https. Next, I made edits to App.js by adding the following line at the t ...

Using PHP to submit a form depending on user selection

Currently, I am working on a basic input form page that includes a submit button. The goal is to have the data from the form written into my MySQL database based on the user's selection. For instance, if the user chooses option X, I want the input da ...

Avoiding conflicts between banners, text, and images for HTML/CSS design

I'm having an issue with the banner I created for my project. It seems to be overlapping with text and images, hiding behind them. How can I fix this? Unfortunately, I can't post the link to my project here due to other files present. The specif ...

Steps for inserting an additional header in an Angular table

https://i.stack.imgur.com/6JI4p.png I am looking to insert an additional column above the existing ones with a colspan of 4, and it needs to remain fixed like a header column. Here is the code snippet: <div class="example-container mat-elevation-z8"> ...

Issue with clientHeight not functioning properly with line breaks in Angular 2 application after ngAfterViewInit

I have successfully created a Gridify page in my Angular 2 application using the Gridify library. To initialize it, I've utilized a custom ngAfterViewChecked method: ngAfterViewChecked() { var selector = document.querySelector('.read-grid& ...

Unable to verify POST $http request using $httpBackend

Currently, I am in the process of writing unit tests to cover the http requests of my app. Using Jasmine and Karma, I have been following a tutorial on how to use $httpBackend from https://docs.angularjs.org/api/ngMock/service/. However, I encountered an e ...

Opera's compatibility with jQuery's Append method allows developers to

I recently wrote a jQuery script that interacts with a JSON feed and dynamically creates HTML code which is then added to a designated div on my WordPress site. Surprisingly, the functionality works flawlessly in all browsers except for Opera - where not ...