Subscribe on changes!

push on reactive array calls onUpdate hook on all child components in v-for list

avatar
Jun 20th 2023

Vue version

3.3.4

Link to minimal reproduction

https://play.vuejs.org/#eNqNU8GO2jAQ/ZVRLoCWJGLZEwqIlXrpoT3RU9NDFg/EJbEj2wEqxL93bMdJdrtdrYUAz7x582bGc4uemyY5txitokzvFW/MJhe8bqQysJNMfjVYw0HJGiZJGgw2YJILgFzg1UEZHoq2MnCz1r2keIHC6BXcBpb73DpZYYrpzAMBFJpWiXADEHix+B1ezQomExdhjyEjsf0MdxhC7OFsBYse7AK4qZAovkgwJQLjukTtNPvjxfyH6vFdql1xQpCtcYRGFbr8LN/yXb5v8uKoquIixkzh768+irpsXBuJ68kbHconrdGUktlee1fB2HffxqHPlLXkOnFtTJpWl9ORSCvRuYc8Dw8jyZ3gDtIPKADus1c5RghY0wzHenNBnyztHxpd6GU0VWGQbhbnv7OX1hgpYLuv+P60HiraPDOWpd7rIrK26iIzW1zMiS/IOccHqdZ5NLWeOXDB8DqjH/+a8ijgVif8QzBrTTgb2V3hweMug3OrsJbn4NWJbkgqTl2SOSxmAbnJ0l6YV5w6yWQOlUfzaLxZwyqCpvVoXFS3kjeQ4kdDO4QM7t1e+mXMRe+Z0tzXm7CLQssKk0oep5N+MaH1yAmNzo7vg5FkjJ9hXxVaU6n7QrGY18WRGtG1ffG49FUR7nVZuaDCvO64Lprkt5aCanOy8s5BU+jfbR5RJfaeR6UxjV6laSua0zEh2emWfKlqheE1xkzW22WyTJ4oqTZjc4K6jl+UvGhUlDCPumfsuFMynlHFCmlICtWHud5gx/neuP7JGZ56dP8LFJmu1Q==

Steps to reproduce

hello, can someone tell me why when adding an element to an array in v-for, onUpdated is called for ALL children? it shouldn't be like this, :key is unique for everyone in the sheet, dom should not be updated, elements are added to the array via .push

at the same time, if you write on the options api, then the hook is not called (in the documentation they are the same updated() and onUpdated() )

What is expected?

onUpdated hook should not be called on child components

What is actually happening?

onUpdated hook is called on all child components in the list after changing array's length

System Info

No response

Any additional comments?

No response

avatar
Jun 20th 2023

Due to the update in todos, the elements are being re-rendered, and TodoItem relies on todos.

avatar
Jun 20th 2023

Due to the update in todos, the elements are being re-rendered, and TodoItem relies on todos.

Hello, thank you for your assistance, but why "updated" hook in options api is not called ? and do you know how to avoid re-render on all child components in computed lists, because they can be really big ?

avatar
Jun 20th 2023

It's called with Options API as well, see here.

The problem is that your child component did not define the remove event, so Vue treats it as a native event passed with attrs to the child, and as its an inline listener, it means a new function is passed down each time - so the child needs to re-render each time in order to apply the new remove listener to the root element.

If you properly declare the component event, no re-renders happen, see here

<script setup>
  import { onUpdated } from 'vue'
  defineEmits(['remove'])
  onUpdated(() => {
  // no longer will be called.
    console.log('component updated')
  })
</script>
avatar
Jun 20th 2023

see here

very very thank You! I need to delve deeper into real project in order to eliminate such problems