setup is a combined API
The optional API is that data, methods, computed, watch, etc. are all separated, but the combined API writes all these things together.
1 Disadvantages of vue2
(1) Use vue2
The Vue2 version intercepts data using Object.defineProperty,
Object changes can be monitored. Because obj has matching getters and setters,
But if you want to add new properties to this object, you will find that the newly added properties do not have getters and setters, and the page will not be able to display the effect.
(2) Use vue3
---Combined APIs
That is, write the responsive data previously written in the data in vue2 in the setup. And through the reactive() method, wrap the data to make it a responsive data
The methods previously written in methods in vue2 are also written in setup.
--- data response
Vue2 uses defineProperty. When there is an array, it cannot match getters and setters for each item in the array.
let m = {
a:1,
b:2,
arr:["a","b","c"]
}
let o = {}
Object.keys(m).forEach((key)=>{
Object.defineProperty(o,key,{
get(){
return m[key]
}
set(){
console.log("修改了")
}
})
})
When we modify the 0th item of the array, the data has changed, but because it does not match the set() method, it cannot be detected and the function cannot be triggered
o.arr[0] = "xxx"
Therefore, the monitoring principle of vue2 is to match the get and set methods with the data objects we passed in. When the data is modified, the get and set methods are triggered to refresh the page, but the object depth and array depth are due to The get and set methods have not been matched yet, the data has been modified, but the set method has not been triggered, and there is no way to refresh the page. For deep objects and deep arrays, recursion must be used. loop + recursion
Vue3 uses Proxy
------reactive writing
You can also use ref. Note that when using ref, you need to access it through .value
// 伪代码,不是真正的实现
const myRef = {
_value: 0,
get value() {
track()
return this._value
},
set value(newValue) {
this._value = newValue
trigger()
}
}