computed
- Computed is used to calculate attributes, and that is a data that depends on other data, so design this data to be computed. Here is a code example
import Vue from "vue/dist/vue.js";
Vue.config.productionTip = false;
new Vue({
data: {
user: {
email: "[email protected]".nickname: "Xiao Ming".phone: "15935778911"}},computed: {
displayName: {
get() {
const user = this.user;
return user.nickname || user.email || user.phone;
},
set(value) {
console.log(value);
this.user.nickname = value; }}},template: `
{{displayName}}
`.methods: {
add() {
console.log("add");
this.displayName = "Little red";// when nickname changes, computed computes its properties, calling displayName without parentheses
}
}
}).$mount("#app");
Copy the code
- Usage scenarios
It is suitable for environments where recalculation is time-consuming and does not require repeated data calculations. The this of all getters and setters is automatically bound to Vue instances. If a data set depends on other data, design it for computed
watch
- Immediate indicates whether to execute the corresponding function on the first rendering. Deep indicates whether to listen for every property value of the object, no matter how deep the nested value is. Here’s an example of a watch
import Vue from "vue/dist/vue.js";
Vue.config.productionTip = false;
new Vue({
data: {
n: 0.obj: {
a: "a"}},template: `
.watch: {
n() {
console.log(Changed "n");
},
obj: {handler(){
console.log("Obj changed");
},
deep:true// Not only is the address of obj changed, but also the property of obj changed
}
}
}).$mount("#app");
Copy the code
- Usage scenarios
When you need to call a function or do something when data changes, you can use Watch to listen for data changes. You can click this link to learn the syntax of Watch on Vue official website