computed属性的特性
computed
属性依赖于data
中的变量。- 计算属性定义的方法必须存在返回值。
- 当依赖的数据发生变化时,会直接重新调用该计算属性的方法。
- 有方法形式和对象形式。方法形式时,为只读
get
。对象形式,可写set
可读get
。
如下:
new Vue({
el: '#root',
data: {
msg: 0
},
computed: {
//dealMsg2只读
dealMsg2 () {
return this.msg + 1
},
//dealMsg可读可写
dealMsg: {
get: function () {
return this.msg + 1
},
set: function (v) {
this.msg = v - 1
}
}
}
})
- 方法形式时,一般无参数。对象形式时,
set
方法需要传入参数,用于改变data
属性中的值