computed -计算属性
用途:被计算出来的属性就是计算属性
用户名展示
import Vue from "vue/dist/vue.js";
Vue.config.productionTip = false;
new Vue({
data:{
user:{
email: "123@qq.com",
nickname: "方方",
phone: "13888888888"
}
},
template: `
<div>
{{ user.nickname || user.email || user.phone}}
</div>
`
}).$mount("#app");
使用computed计算属性来改进
import Vue from "vue/dist/vue.js";
Vue.config.productionTip = false;
new Vue({
data:{
user:{
email: "123@qq.com",
nickname: "方方",
phone: "13888888888"
}
},
computed: {
displayName(){
const user = this.user;
return user.nickname || user.email || user.phone;
}
},
template: `
<div>
{{displayName}}
</div>
`
}).$mount("#app");
computed计算属性最终版
// 引用完整版 Vue,方便讲解
import Vue from "vue/dist/vue.js";
Vue.config.productionTip = false;
new Vue({
data: {
user: {
email: "fangyinghang@qq.com",
nickname: "方方",
phone: "13812312312"
}
},
computed: {
displayName: {
get() {
const user = this.user;
return user.nickname || user.email || user.phone;
},
set(value) {
console.log(value);
this.user.nickname = value;
}
}
},
// DRY don't repeat yourself
// 不如用 computed 来计算 displayName
template: `
<div>
{{displayName}}
<div>
{{displayName}}
<button @click="add">set</button>
</div>
</div>
`,
methods: {
add() {
console.log("add");
this.displayName = "圆圆";
}
}
}).$mount("#app");
列表展示
watch监听
用途:当数据变化时,执行一个函数
// 引用完整版 Vue,方便讲解
import Vue from "vue/dist/vue.js";
Vue.config.productionTip = false;
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 });
}
}
},
// 不如用 computed 来计算 displayName
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");
computed 和 watch 的区别
computed看上去是方法,其实是计算属性。它依赖数据动态显示新的计算结果,计算结果被缓存。computed的值在getter执行后是会缓存的,只有在它依赖的属性值改变之后,下一次获取computed的值时才会重新调用对应的getter来计算
watch是一个data的数据监听回调,当依赖的data的数据变化,执行回调。在方法中会传入 newVal 和 oldVal。可以提供输入值无效,提供中间值 特场景。Vue 实例将会在实例化时调用 $watch(),遍历 watch 对象的每一个属性。如果你需要在某个数据变化时做一些事情,使用watch。