<p v-for="item in items" :key="item.id">
<!-- Content -->
</p>
How to use this: key? Can you give an example? Is it just added for v-for? :key="value" Is the value written arbitrarily?
迷茫2017-05-16 13:25:21
The special attributes of
key are mainly used in Vue’s virtual DOM algorithm to identify VNodes when comparing old and new nodes. If keys are not used, Vue uses an algorithm that minimizes dynamic elements and tries to repair/reuse elements of the same type whenever possible. Using key, it will rearrange the order of elements based on key changes and remove elements where the key does not exist.
Child elements with the same parent element must have unique keys. Duplicate keys will cause rendering errors.
The most common use case is in combination with v-for:
<ul>
<li v-for="item in items" :key="item.id">...</li>
</ul>
It can also be used to force replacement of an element/component instead of reusing it. It may be useful when you encounter the following scenarios:
Completely trigger the component’s lifecycle hooks
Trigger transitions
<transition>
<span :key="text">{{ text }}</span>
</transition>
When text changes, <span> will be updated at any time, thus triggering the transition.
Source reference: https://cn.vuejs.org/v2/api/#key
phpcn_u15822017-05-16 13:25:21
Sometimes when rendering a list, it is necessary to ensure the uniqueness of the data. This key is a unique identifier and must be unique
習慣沉默2017-05-16 13:25:21
Is the key here when updating the list data? The first point: if the data is updated with the same data, the key will be used to render directly. If there is no same data, the key will be compared. Because the keys are not the same, these new The data must be re-rendered. Otherwise, Vue will use the in-place principle to directly use the existing data for rendering. As a result, the data does not achieve the expected effect, but the original dom styles and components cannot be updated? I don’t know if my understanding is correct, but the official website says that input must have a key, but I found that the effect is the same whether there is a key or not. I wonder if anyone can give me an example. I would be very grateful! ! ! ! ! ! ! ! ! ! ! !
大家讲道理2017-05-16 13:25:21
What I said above is too official. In vernacular, it’s easier for you to understand, that is, to improve cycle performance
In fact, it doesn’t matter whether you write this thing or not. Even if you make a mistake, it will not report an error. But it is generally better to write a for loop
伊谢尔伦2017-05-16 13:25:21
It is recommended to read more documents:
http://cn.vuejs.org/v2/guide/...