this.width 和
this.height 时,Vue 收集其做为
vm.area 的依赖,此后
vm.width 或
vm.height 变化时,
vm.area 重新求值。计算属性是基于它的依赖缓存,如果
vm.width 和
vm.height 没有变化,多次读取
vm.area,会立即返回之前的计算结果,而不必再次求值。同样由于
vm.width 和
vm.height 是响应的,在
vm.area 中可以将依赖的属性赋值给一个变量,通过读取变量来减少读取属性次数,同时解决在条件分支中,Vue 有时会无法收集到依赖的问题。实现如下:
const vm = new Vue({
data: {
width: 0,
height: 0,
},
computed: {
area () {
let output = ''
const {width, height} = this
if (width > 0 && height > 0) {
const area = width * height
output = area.toFixed(2) + 'm²'
}
return output
}
}
})vm.width = 2.34
vm.height = 5.67
console.log(vm.area) // 输出 "13.27m²"
通过 ob.js 单独使用 Vue 的属性观察模块
为方便学习和使用,ob.js 将 Vue 中属性观察模块提取并封装了一下。
ob.js GitHub 地址:https://github.com/cnlon/ob.js
安装
npm install --save ob.js观察属性变化
const target = {a: 1}
ob(target, 'a', function (newValue, oldValue) {
console.log(newValue, oldValue) // 3 1
})
target.a = 3添加计算属性
const target = {a: 1}
ob.compute(target, 'b', function () {
return this.a * 2
})
target.a = 10
console.log(target.b) // 20像声明 Vue 实例一样传入参数集合
const options = {
data: {
PI: Math.PI,
radius: 1,
},
computed: {
'area': function () {
return this.PI * this.square(this.radius)
},
},
watchers: {
'area': function (newValue, oldValue) {
console.log(newValue) // 28.274333882308138
},
},
methods: {
square (num) {
return num * num
},
},
}
const target = ob.react(options)
target.radius = 3










