0

https://jsfiddle.net/rohan0793/h7gn8qdv/

So I was trying to implement a simple todo list with computed properties like in the above fiddle. There are 3 lists. All Tasks. Completed Tasks. Incomplete Tasks. The problem is that if I click on the checkbox of an incomplete task in Incomplete List, or a complete task in Completed List, the task below it gets toggled too. I am not sure why this behaviour. Is it because the event is propagating somehow? I tried @click.stop on the checkboxes too but with no luck

1 Answer 1

3

The issue here is you are not using any key attribute in the loop. The key special attribute is primarily used as a hint for Vue's virtual DOM algorithm to identify VNodes when diffing the new list of nodes against the old list.

Without keys, Vue uses an algorithm that minimizes element movement and tries to patch/reuse elements of the same type in-place as much as possible. Thus you are getting the below behaviour:

if I click on the checkbox of an incomplete task in Incomplete List, or a complete task in Completed List, the task below it gets toggled too.

So, to resolve this you simply need to bind key to each loop like:

<li v-for="task in incompleteTasks" :key="task.id">
   <input type="checkbox" v-model=task.completed>{{ task.description }}
</li> 

With keys, it will reorder elements based on the order change of keys, and elements with keys that are no longer present will always be removed/destroyed.

Working Fiddle

Sign up to request clarification or add additional context in comments.

1 Comment

Ah, I added the ids in the array, and I thought I used them too. Stupid of me. Thanks for pointing this out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.