第一步,把computed、methods、watch全部写出,在页面分别输出不同情况下的结果
<body>
<div id="app">
<h2>计算属性:computed</h2>
{{fullname}}
<h2>方法:methods</h2>
{{fullname2()}}
<h2>侦听器:watch</h2>
{{watchFullname}}
<h2>年龄:age</h2>
{{age}}
</div>
<script>
var other = 'This is other.'
const app = new Vue({
el: '#app',
data(){
return {
firstname:'zhang ',
lastname: 'san ',
watchFullname: 'zhangsan',
age: 12
}
},
methods:{
fullname2(){
console.log('调用了fullname2(),使用了一次方法');
return this.firstname+this.lastname+','+other;
}
},
computed: {
fullname() {
console.log('调用fullname,使用了一次属性');
return this.firstname+this.lastname+','+other;
}
},
watch: {
firstname(newValue, oldValue) {
console.log('firstname触发了watch');
this.watchFullname = this.firstname+this.lastname+','+other;
},
lastname(n,o){
console.log('lastname触发了watch');
this.watchFullname = this.firstname+this.lastname+','+other;
}
},
})
</script>
</body>现在来看看结果

可以看到第一次只调用了计算属性computed和方法methods,没有调用监听器watch。
现在在控制台改变firstname的值,可以看到此时计算属性computed、方法methods、监听器watch全部调用了。


下面试试改变与fullname不相关的age的值,可以看到此时只调用了方法methods,所以我们暂时先得出一个结论,vue里面的值只要改变,方法methods都会调用一次。


接下来,可以发现还有一个变量,vue外面定义的other变量,改变一下other的值试一下,可以看到计算属性computed、方法methods、监听器watch全部都没有调用,所以vue外的变量改变不会调用vue。


最后,在上面改变了other的条件下,再次改变firstname的值看看,此时other的值发生了改变,并且计算属性computed、方法methods、监听器watch全部都调用了,所以可以知道,当同时改变vue内部的变量值和vue外面的变量值才会使外面的变量改变。

此时,还有一个lastname变量的没有改变过,lastname与firstname的改变一样,只不过是触发的lastname的监听事件。


最后总结一下,通过上面的改变变量值可以发现,计算属性computed有缓存属性,当改变不在计算属性里面值的时候,计算属性不会调用,但是methods方法只要发生了vue内部的值改变就会调用,所以在使用的时候,计算属性性能更好。