1.计算属性(存在缓存机制,性能高,代码精简)
computed:{
计算属性中 函数中的变量 如果没有变化的话,那么就不会在重新执行 这就是具备缓存机制的
fullName:function(){
console.log("计算了一次");
return this.lastName+' '+this.firstName;
}
}
2.methods 触发事件函数 写在这里 缓存机制没有:
fullName(){
console.log("计算了一次");
return this.lastName+' '+this.firstName;
}
3.watch 侦听器 具备缓存机制 代码不精简 虽然计算属性在大多数情况下更合适,但有时也需要一个自定义的侦听器。这就是为什么 Vue 通过 watch
选项提供了一个更通用的方法,来响应数据的变化。当需要在数据变化时执行异步或开销较大的操作时,这个方式是最有用的。
watch:{
firstName:function(){
console.log("计算一次水性");
this.fullName = this.lastName+' '+this.firstName;
},
lastName:function(){
this.fullName = this.lastName+' '+this.firstName;
}
}
4.计算属性中的get set方法:
<script>
var app = new Vue({
el:'#app',
data:{
firstName:'明',
lastName:'小',
},
computed:{
fullName:{
get:function () {
return this.lastName+' '+this.firstName;
},
set:function(value){
var arr = value.split(' ');
this.firstName = arr[0];
this.lastName = arr[1];
}
}
}
});
</script>