background
If key is specified as index during dynamic deletion of a v-for rendered list, rendering errors may occur. For example, if your list has two rows, you delete the first row, but the second row disappears.
parsing
Let’s say you have two rows in your list, and when you delete the first row, the key in the second row becomes the key in the first row, and they’re the same. Virtualdom-based libraries treat components with the same key as the same component and do not update views.
In other words, you delete the first row, the expected second row becomes the first row, and the result is that because the key is the same, the first row stays the same, but the second row disappears.
Why didn’t I reappear
Most of the time we do not reproduce this problem even if we use index as key, which seems inconsistent with our analysis above. But in fact, the “use index as key and nothing will happen” scenario looks like this:
-
Step 1: Delete the first row by modifying the data. Data changes cause VUE to update the view. During the update process, it is found that the key is the same, and finally the first row remains unchanged, but the second row disappears. This is the first render.
-
Step 2: The VirtualDOM in the first line does not change, but the component props in the first line is changed from the props in the first line to the props in the second line. As a result, the component in the first line needs to update the view with the new props in the second line. This is the second render.
In other words, the “use index as key and nothing will happen” scenario is due to render twice before the view is properly updated.
So when can it reappear
If you only trigger render once in the process of deleting the first row, the problem will recur. That is, if each row of components does not depend on any “reactive” data, then there is no second render and the problem can reproduce!
The above two cases in the DEMO: codesandbox. IO/s/wonderful…
Special case: If the component in the list is a simple text node, and the text node has no props, does it reproduce the problem?
The answer is “no”. Vue’s Diff process has special treatment for text nodes, overriding the “old text node” with the “new text node” regardless of the key.
conclusion
Deleting a list in a component that uses non-text nodes and does not rely on responsive props will result in view clutter.