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

Issues with Pageinit and Ready Event Timings

Check out this fiddle where I am experiencing an issue related to pageinit and ready events In the fiddle, everything functions properly using onLoad and onDOMready. This includes: The subject listings are loaded correctly with a popup displaying module ...

An issue arises when attempting to simultaneously utilize withDefaults and defineProps within the <script setup> block in a Vite + Vue project

I'm currently working on a project that involves using Vite + Vue. However, I've encountered an error in the code snippet below. Through my research, I discovered that the combination of withDefaults and defineProps within the <script setup> ...

showing the data in a textbox using AJAX retrieved information

I have a table where additional rows can be added by the user with the click of a JavaScript function. Each row contains a drop down list, and based on the selected value, an AJAX script fetches some values to display in corresponding textfields within th ...

What steps can be taken to prevent a Javascript Timeout Exception when attempting to launch a new browser window?

Recently, I have encountered an issue while running my test cases on a Linux server. Specifically, when trying to open a new window using Robot Framework, I consistently receive a Timeout Exception. This problem seems to be isolated to the server environm ...

Is it possible to trigger a JavaScript function and an AJAX command with just one button click?

I'm looking to achieve a specific functionality using one button within a form. The requirements are as follows: 1) When the button is clicked, it should trigger a JavaScript function that performs animations such as fadeout and fadein. 2) Following ...

function executed when meteor template finishes loading all content

Here is a template structure that I am working with: <template name="mainEvents"> <section class="main-events-list events-list js-content-slider"> {{#each events}} <div class="events-list-item"> &l ...

Discovering the required rotation angle for an object to directly face another using JS HTML5 CANVAS

Hey there, I'm currently working on a game project in Javascript where I have a player and a cursor. I already know the positions of both objects, but what I need help with is determining the angle in degrees or radians that the player needs to rotate ...

Mapping an array using getServerSideProps in NextJS - the ultimate guide!

I'm facing an issue while trying to utilize data fetched from the Twitch API in order to generate a list of streamers. However, when attempting to map the props obtained from getServerSideProps, I end up with a blank page. Interestingly, upon using co ...

Which javascript library provides the top-notch SVG graphics support for Internet Explorer and other web browsers?

Currently, I am developing a web application using javascript and jquery that involves drawing numerous rectangles and lines connecting them. It seems like I need to find an SVG graphics library to create lightweight components (approximately 300). The ch ...

Troubleshooting: How to resolve the issue of receiving undefined values when passing API data to a child component with Axios in React

I am encountering difficulties in retrieving data that I pass to a child component. The issue may be related to the Promise not being resolved at the time of access, but I am unsure how to address it. My goal is to ensure that the data is fully retrieved f ...

Creating a "select all" feature in an HTML multiple select box with jQuery - a step-by-step guide

I'm currently working on an HTML form that includes a multiple select box. I am looking to create a "select all" option within the multiple select box so that when a user clicks on that option, all other options in the select box are automatically sel ...

Difficulty Loading Static JavaScript File in Express.js

Currently in the process of setting up an express server with create-react-app. Encountering this error in the console: Uncaught SyntaxError: Unexpected token < bundle.js:1 Upon clicking the error, it directs me to the homepage htm ...

Switch up the animation based on the state in AngularJS

In my AngularJS application, I have implemented CSS animations for transitioning between states. The animations involve sliding content from left to right with specific timings and transforms. .content.ng-enter, .content.ng-leave { -webkit-animation-t ...

Discover the method for creating URLs that are relative to the specific domain or server on which they are hosted

I need to adapt my menu bar to cater for different server environments: <a href="http://staging.subdomain.site.co.uk/search/page">Menu</a> The main source site is hosted on an external subdomain from an API service, and I want the URLs in my ...

Is there a way for me to view the names of the images I am uploading on the console?

Recently, I've started using express and NodeJs. I've created a function called upload that is responsible for uploading images. Here is the code: const fs = require("fs"); var UserId = 2; var storage = multer.diskStorage({ destination: functi ...

Sending Email Form in PHP using JQuery and Ajax for seamless user experience

Looking to create an email form in HTML with PHP, but running into the issue of the page reloading after submitting? Many people turn to jQuery and AJAX to solve this problem. While you may have come across solutions on Stack Overflow, as a non-native Engl ...

The react component is not defined within the <Popup></Popup> tag

SOLVED: Big thanks to everyone who offered their assistance. Upon further investigation, I discovered that in the library I was using, the trigger={} functionality is specifically designed to work only with a button element. To address this issue, I took ...

What is the best way to invoke my Python function within my JavaScript file?

I am facing an issue with using my Python function in JavaScript. Although the actual code I am working on is more complex, I have simplified it to demonstrate the problem below: main.mjs dbutils.notebook.run("./aPythonFile.py", 5, {"parame ...

Having trouble adding a test card to the Google Pay testing environment and calculating the order total

How can I display the order total in GooglePay payment sheet? I could not find any documentation on this. Is it possible to do so? Even though I am using the TEST environment, I am unable to add any test card as mentioned in the URL provided below. Additio ...

Chrome Developer Tools - Array Length Discrepancies

While exploring Chrome DevTools, I came across an inconsistency that caught my attention. The screenshot above shows the issue I encountered. Initially, it indicated that the object contained a Body and a Head, with the head being an array of length 1. Ho ...