computed 和 watch 的区别:
computed 计算属性。
不需要加括号,根据依赖是否变化来缓存。
语法:computed :{ [key: string]: Function | { get: Function, set: Function } }
代码示例如下:
import Vue from "vue/dist/vue.js";
new Vue({
data: {
user: {
email: "xxxxx@qq.com",
nickname: "xxx",
phone: "138xxxxx"
}
},
computed: {
displayName: {
get() {
const user = this.user;
return user.nickname || user.email || user.phone;
},
set(value) {
console.log(value);
this.user.nickname = value;
}
}
},
template: `
<div>
{{displayName}}
<div>
{{displayName}}
<button @click="add">set</button>
</div>
</div>
`,
methods: {
add() {
console.log("add");
this.displayName = "圆圆";
}
}
}).$mount("#app");
watch 监听侦听。
数据变化的时候执行一个函数,一旦data变化就执行得函数。
语法:watch:{ [key: string]: string | Function | Object | Array }
代码示例如下:
import Vue from "vue/dist/vue.js";
new Vue({
data: {
n: 0,
history: [],
inUndoMode: false
},
watch: {
n: function(newValue, oldValue) {
console.log(this.inUndoMode);
if (!this.inUndoMode) {
this.history.push({ from: oldValue, to: newValue });
}
}
},
template: `
<div>
{{n}}
<hr />
<button @click="add1">+1</button>
<button @click="add2">+2</button>
<button @click="minus1">-1</button>
<button @click="minus2">-2</button>
<hr/>
<button @click="undo">撤销</button>
<hr/>
{{history}}
</div>
`,
methods: {
add1() {
this.n += 1;
},
add2() {
this.n += 2;
},
minus1() {
this.n -= 1;
},
minus2() {
this.n -= 2;
},
undo() {
const last = this.history.pop();
this.inUndoMode = true;
console.log("ha" + this.inUndoMode);
const old = last.from;
this.n = old; // watch n 的函数会异步调用
this.$nextTick(() => {
this.inUndoMode = false;
});
}
}
}).$mount("#app");
watch的deep,immediate :
deep深入查看:为了发现对象内部值的变化,可以在选项参数中指定deep: true
。 注意监听数组的变更不需要这么做。
immediate第一次渲染是否要执行这个函数:在选项参数中指定immediate: true
将立即以表达式的当前值触发回调。
语法:
![6467e5bb6b70d33975db8fb9b9db5668.png](https://img-blog.csdnimg.cn/img_convert/6467e5bb6b70d33975db8fb9b9db5668.png)
deep代码示例如下:
vm.$watch('someObject', callback, {
deep: true
})
vm.someObject.nestedValue = 123
// callback is fired
immediate代码示例 如下:
vm.$watch('a', callback, {
immediate: true
})
// 立即以 `a` 的当前值触发回调