What is responsive

If you change vm.n, the n in the interface will change in response

const vm=new Vue({data:{n:0}})
Copy the code

Data bug in Vue

A code

new Vue({
    data: {},template:` 
      
{{n}}
`
}).$mount("#app") Copy the code

N is not defined but referenced

Code 2

New Vue({data:{obj:{a:0//obj. template:` <div> {{obj.b}} <button @click="setB">set b</button> </div> `, methods:{ setB(){ this.obj.b=1; }}}).$mount("#app")Copy the code

The page will not display a 1 because obj. B never existed in the first place

The solutionVue.set

New Vue({data:{obj:{a:0//obj. template:` <div> {{obj.b}} <button @click="setB">set b</button> </div> `, methods:{ setB(){ Vue.set(this.obj,'b',1); } } }).$mount("#app")Copy the code

Role is

  • Add a new key
  • Automatically create agents and listeners
  • Trigger UI update, but not immediately // This is vUE’s automatic function

What if there is an array in data

Look at the following code

new Vue({ data:{ array:["a","b","c"] }, template:` <div> {{array}} <button @click="setD>set d</button> </div> `, methods:{ steD(){ this.array[3]="d"; / / / / this page does not show still d array in an array: [0: "a", 1: "b", 2: "c", length], add after the detection is less than this. $set (this array, 3, "d"); / / so you can show d, but can't write the data first}}}) in advance. $mount (" # app ");Copy the code

In the above code, if data is an array, d cannot be obtained using traditional methods; Vue. Set does, but we can’t actually get the length of the array

new Vue({
    data:{
        array:["a","b","c"]
        },
        template:`
            <div>
                {{array}}
                <button @click="setD">set d</button>
             </div>
         `,
         methods:{
             setD(){
                 this.array.push("d");
                 console.log(this.array)
             }
         }
    }).$mount('#app')
Copy the code

When I open the console and look at the array methods, I find that the array methods have a new layer. Look at the following code

class VueArray extends Array{ push(.. Args){const oldLength =this.length//this current array super.push(... args) for(let i=oldLength; i<this.length; i++){ Vue.set(this,i,this.[i]) } } }Copy the code

conclusion

Object is the new key

  • Vue has no way to listen and proxy in advance, so it needs to use set to add keys, create listeners and proxies, and update the UI
  • It is best to add all the attributes in advance without adding new keys
  • But if it’s an array, you usually can’t add good values directly

Array new key

  • You can also use set to add keys, create listeners and proxies, and update the UI
  • But Yuxi tampered with 7 apis to make it easier to add and delete arrays
  • The new API automatically handles listeners and proxies, and updates the UI