Prepare a list in vue

I have a component named task that contains a string of form inputs related to the task. tasks

retrieved from GET JSON request (existing records).

<task v-for="task in tasks" :task="task"></task>

      

I now have a button to add a new blank line of inputs so they can add new entries.

<button type="button" @click="addTask()">New</button>

      

I tried to disable empty object for tasks:

addTask() {
    this.tasks.unshift({});
},

      

However, this just duplicates the last line of my tasks, rather than adding a new line to the beginning of the tasks.

What's the best way to add items to an existing list?

+3


source to share


1 answer


When using a directive v-for

on a component, you need to specify the attribute key

by providing a value that will be unique for each component. Otherwise Vue will try to reuse the elements.

From the documentation :

The special attribute key

is mainly used as a hint for the Vues virtual DOM algorithm to identify VNodes when comparing the new list of nodes with the old list. Keyless Vue uses an algorithm that minimizes element movement and tries to patch / reuse elements of the same type in place as much as possible.



In your case, the best way to specify a key would be to bind a property id

to each task

and use it as a key:

<task v-for="task in tasks" :task="task" :key="task.id"></task>

      

+1


source







All Articles