0
点赞
收藏
分享

微信扫一扫

computed和watch的区别? (vue)

千行 2022-01-23 阅读 89

1.computed 计算属性(必须有返回值 (return)),数据受其他数据的影响,一般用于购物车计算等。
注意:依赖的数据发生改变时,计算属性才会重新计算

computed: {
// 第一种写法:方法写法
// computedTotal () { // 名字不在data中定义 // === computed:function(){}
// return this.num1 + this.num2
// },
// 第一种写法:对象写法
computedTotal: {
get () { // get:function(){}
return this.num1 + this.num2
},
set (val) { // set:function(){}
}
}
},

2.watch 监听,当观察的值发生改变,页面就立刻改变。

 watch: {
/*对象写法, 名字必须定义了*/
watchTotal: {
handler () {
this.watchTotal = this.num1 + this.num2
},
immediate: true, // 立即执行一次 handler
deep: true, // 深度监听
},
// 方法写法
// watchTotal (newValue, oldValue) {
// this.watchTotal = this.num1 + this.num2 // 不起反应的时候就要对象写法
// },
},

加载顺序: props - > methods - > data - > computed - > watch

举报

相关推荐

0 条评论