1. computed
- 具有缓存性,如果数据没有发生改变则页面不会重新渲染
- 会立即执行
- 适合多个值影响一个值,例如总价由 数量,单价,折扣计算得到
computed: {
total() {
return this.count * this.price * this.discount
}
}
- 计算属性默认只有getter,也可以设置setter,例如用户可用金额固定,想要购买的商品数量固定,商品单价固定,此时需要计算一下商品折扣,看是否在折扣范围内则需要使用setter计算
total: {
get() {
return this.count * this.price * this.discount
},
set(newValue) {
this.discount = newValue / this.count / this.price
}
},
2. watch
- 默认不会立即执行,可设置immediate:true 将立即执行
- 一个值影响多个值,适合异步操作或者较大开销的情况
- 当为对象时,deep: true
obj: {
immediate:true,
deep:true,
handler(newValue, oldValue) {
console.log(newValue, oldValue)
}
}