Vue data responsive
- Responsivity is a form of response to changes in the outside world.
- const vm = new Vue({data:{n: 0}})
- When changing vm.n or data.n, render(data…) N will respond to that response.
- This linkage process is the data response of vUE.
- Vue currently implements data responsiveness through Object.defineProperty
Understand options.data in depth
Deep into the responsivity principleThe document
What exactly did Vue do with Data
The ES6Getter and setter
getter
It’s just a function name without parentheses, that’s all
Type case
Let obj0 = {name: "gao ", name:" yuyuan ", age: 18}; Let obj1 = {last name: "gao ", last name:" yuan yuan ", last name () {return this. Name + this. }, age: 18 }; Console. log(" Requirement 1: "+ obj1. name ()); // Can you delete the parentheses after the name? No, because it's a function. Let obj2 = {family name: "high ", family name:" yuan yuan ", get family name () {return this. Name + this. }, age: 18 }; Console. log(" Requirement 2: "+ obj2. name); // Summary: This is how getters are used. Function without parentheses, that's all. Let obj3 = {surname: "gao ", surname:" yuan yuan ", get name () {return this. Name + this. }, set name (XXX){this. Surname = XXX [0] this. Name = xxx.substring(1)}, age: 18}; Obj3. name = 'gao Yuanyuan' console.log(' Requirement 3: last name ${obj3. ${obj3. name} ') // Summary: this is how setters work. A new value must be received to trigger the set functionCopy the code
Object.defineProperty: directly defines a new property on an object, or modifies an existing property of an object, and returns the object.
You can add getters/setters to objects to monitor reads and writes of properties
var _xxx = 0
Object.defineproperty(obj3, 'xxx',{
get(){
return _xxx
},
set(value){
_xxx = value
}
})
Copy the code
There are problems with Object.defineProperty in vue
Object.defineProterty(obj,’n’,{… }) there must be an ‘n’ in it to listen on or delegate obj.n
1. Declare the key 2. Use Vue. Set or this
Vue.set(this.obj, 'b',1)
this.$set(this.obj,'b',1)
Copy the code
When you writevm = new Vue({data: myData})
Vue did two things
-
This will make the VM a proxy for MyData, and you can also use this to access the VM
-
All properties of MyData are monitored
Why monitor, in case the attributes of MyData change and the VM doesn’t know about it
The VM can call render(data)
UI = render(data)
What if there is an array in data
Tamper with the API of the array, seven apis will be tampered with by Vue, after the call will update the UI
push()
pop()
shift()
unshift()
splice()
sort()
reverse()