1 计算属性的本质
每个计算属性都包含一个getter和setter,一般情况下我们只使用getter来读取,作为只读属性。
计算属性的完整写法
<div class="app">
<h2>{{fullName}}</h2>
</div>
<script src="js/vue.js"></script>
<script>
const app = new Vue({
el: '.app',
data: {
firstName: 'Tom',
lastName: 'Jack',
},
computed: {
fullName: { /* 完整写法 */
set: function () {},
get: function () {
return this.firstName + ' ' + this.lastName;
},
},
fullName: function () { /* 常用写法 */
return this.firstName + ' ' + this.lastName;
},
},
});
</script>
上列代码中,computed中两个fullName的作用一样,第一种写法是完整写法,但由于一般不适用set函数,所以常使用第二种写法,这也解释了为什么上面使用fullName的时候为什么不加括号,因为本质上是作为属性使用的。运行fullName时,实际上是在调用fullNmae中的get方法。
使用set方法
<div class="app">
<h2>{{fullName}}</h2>
</div>
<script src="js/vue.js"></script>
<script>
const app = new Vue({
el: '.app',
data: {
firstName: 'Tom',
lastName: 'Jack',
},
computed: {
fullName: {
set: function (newValue) {
const name = newValue.spilt(' ');
this.firstName = name[0];
this.lastName = name[1];
},
get: function () {
return this.firstName + ' ' + this.lastName;
},
},
},
});
</script>
上列代码可以通过给app.fullName赋值,使用set方法修改data中的数据,然后再用get方法读取出来。
2 computed的缓存
<div class="app">
<h2>{{getFullName()}}</h2>
<h2>{{getFullName()}}</h2>
<h2>{{getFullName()}}</h2>
<h2>{{getFullName()}}</h2>
<!-- 通过methods -->
<h2>{{fullName}}</h2>
<h2>{{fullName}}</h2>
<h2>{{fullName}}</h2>
<h2>{{fullName}}</h2>
<!-- 通过computed -->
</div>
<script src="js/vue.js"></script>
<script>
const app = new Vue({
el: '.app',
data: {
message: '起飞',
firstName: 'Tom',
lastName: 'Jack',
},
methods: {
getFullName: function () {
console.log('getFullName');
return this.firstName + ' ' + this.lastName;
},
},
computed: {
fullName: function () {
console.log('fullName');
return this.firstName + ' ' + this.lastName;
},
},
});
</script>
上列代码运行后,通过log打印可以看到,gerFullName调用了四次,而fullName只调用了一次。表明computed具有缓存的功能,只要当data中的数据变化时,才会重新调用fullName,当使用较多时,computed性能会更高。