Home > other >  Vue.js why can't I create unique key for v-for by calling a method?
Vue.js why can't I create unique key for v-for by calling a method?

Time:05-04

I came across a case where I need to iterate from n to 10 using a v-for, and I wanted to use the uuid v4 method to generate a unique key for each loop. I've tried different ways to make the call but it just doesn't seem to be possible and I would like to understand why. I also tried to log the function but nothing showed up.

[Vue warn]: Duplicate keys detected: 'function() {
    [native code]
}'. This may cause an update error.
<span v-for="index in getTableLength" :key="getUuid">{{n}}</span>
import {v4 as uuidV4} from 'uuid'
 methods: {
    getUuid(){
        return uuidV4()
     },

Thank's for the help

CodePudding user response:

:key does not evaluate the function like a method call. Because it is a key part in optimizing the update mechanism, it turns any value it gets into a string (if not already a string) and then uses that for comparison. So here you see the result of what happens when you call toString() on a function.

Use it like so instead:

<span v-for="index in getTableLength" :key="getUuid()" />

But this will basically be the same as not setting a v-bind:key in the first place, because every invoke will produce a new result. This means that the node will never be matched and always recreated, no reuse between render updates. So it actually may be worse because that is the same as having no key, but now you also call a function as well.

I personally tend to create arrays with preformatted data in a computed getter instead.

CodePudding user response:

You are not calling your UUID function - you're merely passing a reference to it. Add braces () to actually call the function.

  • Related