Vue has an instruction that I’m sure everyone has written down, which is V-for, which is used whenever there are repeated elements that need to be traversed, but it also has an additional condition, which is that a key must be added. Why is that?
Let’s first go to the vUE website to see what it says:
The website has a concept of maintaining state, which means that we are using V-for to render the list of elements, which defaults to an ‘in-place update strategy’. What is this “update in place”?
Let’s take a look at a very simple set of ul -> Li constructs:
The page looks like this:
It’s a very simple structure, and when we click on the button, we add a number four to the array, and by looking at the page elements, we see that the first three items are unchanged, but a fourth item is added. And at this time, we finally add an element in the array, click on the button to add operation to an element in the front of the array increases, then will happen interesting things – page elements will flash, show on the page elements have changed, careful observation will find that in fact the preceding three paragraphs will only update the content of li, dom structure has not changed, And the fourth term is the whole new one. Maybe it’s a little abstract, but let me draw a picture
As shown, the first time you add an element to the end of the array. When adding new items, VUE will first compare the list before and after. Since the first three items have no change, it can directly add a new structure at the end.
The second time I add an element to the front of the array. At this time, the new order of the list has changed, became the first array, 4 other elements in turn off, so in the new no. 4 in will find the original dom structure first, because on the update will not move the order of the dom element, but still in dom elements, we only need to update the content, But the third item, now in the fourth bit of the array, doesn’t have enough structure, so you have to add a DOM structure.
Key =’item’; because the list is a simple array, there is no ID, so we will use the whole item as an ID (we want to make sure that the ID is unique).
As shown in the figure, when v-for traverses the element with a unique key, it will be different. Because the key value is unique, so when updating, the new element will be compared according to the key. If the key exists, then the element will not change. Just create a new DOM in front of element 1.
Key :’index’ is the default value of the ‘update in place’ policy.
If you haven’t noticed, the vue website also mentions —- ‘only applies to non-dependent child component states or temporary DOM states’. This sentence is also easy to understand. ➤ In the foreground, check the status of each li element in the foreground by opening the checkbox. But when you add a new element in the foreground, check the status of each li element in the foreground by opening the checkbox in the foreground. This is the vue’ update in place ‘pot.