3.computed setter
{{site}}
var vm = new Vue({
el: '#app',
data: {
name: 'Google',
url: 'http://www.google.com'
},
computed: {
site: {
// getter
get: function () {
return this.name + ' ' + this.url
},
// setter
set: function (newValue) {
var names = newValue.split(' ')
this.name = names[0]
this.url = names[1]
}
}
}
})
// 調(diào)用setter,vm.name 和 vm.url 也會(huì)被對(duì)應(yīng)更新
vm.site = '51code http://www.51code.com';
document.write('name: ' + vm.name);
document.write('
');
document.write('url: ' + vm.url);
運(yùn)行結(jié)果:
從實(shí)例運(yùn)行結(jié)果看在運(yùn)行vm.site = '51code http://www.51code.com';時(shí),setter就會(huì)被調(diào)用,同時(shí)vm.name和vm.url也會(huì)被對(duì)應(yīng)更新。
在使用計(jì)算屬性computer,在必要時(shí)可以設(shè)置setter。