0 votes
in VueJS by

1 Answer

0 votes
by

When rendering a list of items, the key attribute allows Vue to keep a track of individual Vnodes. The key value must be unique as it acts as an identity.

If the key attribute is NOT used and if the contents of the list change (such as sorting a list), the Virtual DOM, instead of moving elements up or down, prefers to patch the nodes in place with the updated data to reflect the change. This is the default mode and is efficient. 

When a unique key value IS provided, the elements will be reordered based on the change to the keys (and not patched in place with new data) and if keys are removed (such as when items in a list are deleted), then the corresponding nodes are destroyed or removed as well. 

 

Here, we have a parent component rendering a list of child components. We see three list items being rendered as three child component nodes. Each of these child components contains a span tag and an input box and possibly a local state object (optional). Let’s examine two scenarios now: 

When NOT using the key attribute: If the list is re-sorted for instance, Vue will simply patch the already present three nodes with the re-sorted data, instead of moving the nodes. This will work fine as long as the user has not typed in/changed the local state of one or more of these child components. So, let’s say a user has typed in component no. 3’s input box. When the list is re-sorted, the span tag’s content for component no. 3 will change however the input box will remain there with the user typed content/stateful data. This is because there is no way for Vue to identify component no. 3 and it simply repatches what it sees as updated data i.e. the contents of the span tag.

When the key attribute IS used on the child component, Vue knows the identity of the component and when the list is re-sorted, the nodes will be moved instead of being re-patched. This will ensure the manually edited input box travels to its new position along with the entire component.

The key attribute can also be used when conditionally rendering components/elements to signal Vue about the uniqueness of elements and to ensure elements are not re-patched with new data.

Related questions

0 votes
asked Mar 6, 2022 in VueJS by sharadyadav1986
0 votes
asked Aug 30, 2023 in Android Library by SakshiSharma
...