- Vue.js 2 Web Development Projects
- Guillaume Chau
- 313字
- 2021-07-02 22:34:34
The key special attribute
When Vue is updating a list of DOM elements in a v-for loop, it tries to minimize the number of operations applied to the DOM, such as adding or removing elements. This is a very efficient way of updating the DOM in most cases and can improve the performance.
In order to do this, it reuses elements as much as it can and patches the DOM only where it is needed to have the desired result. It means repeated elements will be patched in place and won't be moved if an item is added or removed from the list. However, this also means that they won't animate if we apply transitions on them.
The following is a schema of how this works:

In this schema, we remove the third item in the list, which is c. However, the third p element will not be destroyed--it will be reused with the fourth item in the list, which is d. Actually, this is the fourth p element that is destroyed.
Fortunately, we can tell Vue how each element is identified so that it can reuse and reorder them. To do that, we will need to specify a unique identifier with the key special attribute. For example, each of our items could have a unique ID that we would use as the key:

Here, we specify keys so that Vue knows the third p element should be destroyed and the fourth p element moved.
The key special attribute works like a standard attribute, so we need to use the v-bind directive if we want to assign a dynamic value to it.
Back to our cards, we can use the unique identifier on the cards as the key:
<card v-for="card of cards" :def="card.def" :key="card.uid" @play="handlePlay(card) />
Now, if we add, move, or delete a card item in the JavaScript, it will be reflected with the right order in the DOM.
- C語言程序設(shè)計(jì)習(xí)題解析與上機(jī)指導(dǎo)(第4版)
- Linux核心技術(shù)從小白到大牛
- 數(shù)據(jù)結(jié)構(gòu)簡明教程(第2版)微課版
- 精通API架構(gòu):設(shè)計(jì)、運(yùn)維與演進(jìn)
- Python Data Analysis(Second Edition)
- Java EE 7 Development with NetBeans 8
- 鋒利的SQL(第2版)
- C語言程序設(shè)計(jì)案例精粹
- Vue.js應(yīng)用測試
- Java圖像處理:基于OpenCV與JVM
- 3ds Max 2018從入門到精通
- Using Yocto Project with BeagleBone Black
- C++ Data Structures and Algorithm Design Principles
- SQL Server 2014數(shù)據(jù)庫設(shè)計(jì)與開發(fā)教程(微課版)
- 深度學(xué)習(xí):基于Python語言和TensorFlow平臺(視頻講解版)