一、Get
一般情况下,我们只是使用了computer中的gettter属性,默认只有 getter,我们只是单纯的使用了gettter属性
就像下面的例子
二、Set
只有当computed监测的值变化的时候,也就是我下面例子中的fullName变化的时候,set才回被调用
<div class="hello">
<div id="example">
<p>firstName值: {{firstName}}</p>
<p>fullName值: {{fullName}}</p>
</div>
<button @click="ClickCeshi">点击改变fullName的值</button>
</div>
data () {
return {
firstName: 'Foo'
}
},
methods: {
ClickCeshi () {
this.fullName = 'fullName的新值'
}
},
computed: {
fullName: {
get: function () {
console.log('调用了getter属性')
return '***' + this.firstName + '***'
},
set: function (newValue) {
console.log('调用了settter属性')
console.log(newValue)
this.firstName = newValue
}
}
}
上面的点击事件,改变fullName的值
没有点击点击事件之前,页面的输出:可以看到,在没有进行任何操作之前getter就会自动执行,页面中的fullName已经改变
点击过点击事件之后,调用乐set,便可以进行操作了
参考文献:vue官网:计算属性和侦听器 — Vue.js