Transfer: https: //www.runoob.com/vue2/vue-computed.html
the site better example, and relatively easy to understand.
- One embodiment, to achieve reverse a string
<body>
<div id="app">
<p>原始字符串: {{ message }}</p>
<p>计算后反转字符串: {{ reversedMessage }}</p>
</div>
<script>
var vm = new Vue({
el: '#app',
data: {
message: 'Runoob!'
},
computed: {
// 计算属性的 getter
reversedMessage: function () {
// `this` 指向 vm 实例
return this.message.split('').reverse().join('')
}
}
})
</script>
</body>
The result:
a calculation in Example declares a property reversedMessage.
Function will be used to provide the property getter vm.reversedMessage.
vm.reversedMessage depends on vm.message, when vm.message changes, vm.reversedMessage updated.
- The difference between the computed and methods
- is computed based on its dependency cache, will be re-evaluated only if its dependencies change.
- The use of methods, re-rendering, the function will always be re-called.
- It can be said computed using performance will be even better, but if you do not want to cache, you can use the methods properties.
- computed getter and setter
<body>
<div id="app">
<p>{{ site }}</p>
</div>
<script>
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[names.length - 1]
}
}
}
})
// 调用 setter, vm.name 和 vm.url 也会被对应更新
vm.site = '菜鸟教程 http://www.runoob.com';
document.write('name: ' + vm.name);
document.write('<br>');
document.write('url: ' + vm.url);
document.write('<br>'+vm.site + "...");
</script>
</body>
operation result:
- computed property defaults only getter, but if necessary you can also provide a setter
- In operation vm.site = 'novice tutorial http://www.runoob.com' From the results of Examples run; time, setter is called, vm.name vm.url and will be a corresponding updated.