<! -- item. Vue surveillance data - > < template > < div > {{' obj + obj}}, {{' id '+ id}}, {{data}} < / div > < / template > < script > import leftConsoleMixin from '@/mixin/leftConsole' let key = 1 export default { name: `item`, mixins: [leftConsoleMixin], props: { obj: Object, id: [String, Number] }, data() { return { data: key++, tag: this.$vnode.tag } }, watch: { obj: { handler(newVal) { if (newVal) { console.log(this.tag, 'watch', this.data) } }, immediate: true, deep: true }, id: { handler(newVal) { if (newVal) { console.log(this.tag, 'watch', this.data) } }, immediate: true } } } </script>Copy the code
Perform operations
  1. Array method and array subscript changes
  2. Simulated paging
  3. The contents of the array stay the same, the subscripts change
  4. Add 2 and 3
  5. Deep obJ object changes
  6. Change by set
The test data
{ lists: [ { id: 1, a: 1, b: 1, c: 1 }, { id: 2, a: 1, b: 1, c: 1 }, { id: 3, a: 1, b: 1, c: 1 } ], temp: [ { id: 1, a: 1, b: 1, c: 1 }, { id: 2, a: 1, b: 1, c: 1 }, { id: 3, a: 1, b: 1, c: 1 } ], deepObj: [{ a: [{ b: [{ d: 1 }], c: 1}}}]]Copy the code
Scene 1:
Obj <div> <item V-for ="(obj, index) in lists" :key="index" :obj="obj"/> </div> <item V-for ="obj in lists" :key="obj. Id ":obj="obj" /> </div>Copy the code

Lists the splice (0, 1)

Index triggers the watch of component 1,2, and deletes 3

If id is used, delete 4

list.reverse()

Index triggers 1,3 watch

When id is used, the location is directly changed

If the key is id and the component index can be manipulated accurately, the value is reused by transforming the input

Scene 2:
Id <div> <item V-for ="{id} in lists" :key="id" :id="id" /> </div> Id <div> <item V-for ="({id}, index) in lists" :key="index" :id="id" /> </div>Copy the code

Lists the splice (0, 1)

Index, delete 3, update 1,2 values

Id to remove 4

lists=temp

Reference address changed, pass value unchanged, no update triggered

Scenario 3:
<div> <item V-for ="(obj, index) in lists" :key="index"/> </div> <div> <item V-for ="obj in lists" :key="obj.id" /></div>Copy the code

list.reverse()

The passed value does not change and updates are not triggered

lists=temp

Reference address changed, pass value unchanged, no update triggered

lists.push(lists.shift())

The passed value does not change and updates are not triggered

Conclusion:
  1. Rendering with key as a unique value changes the position of the component, while using index as a key changes the value passed into the component
  2. Component updates are not triggered when the reference address of the outer object changes without the value of the component being passed in