目录
computed、methods、watch理解
computed:计算属性将被混入到Vue实例中,所有getter和setter的this上线自动绑定到Vue中
methods:methods将被混入到Vue实例中,可以直接通过vm实例访问这些方法,或者指令表达式中使用。方法中的this自动绑定为Vue实例。
watch:是一种通用的观察和响应Vue实例上的数据变动。适用于异步操作。
简单地理解
computed在HTML&DOM加载后马上执行,如赋值
methods则必须要有一定的触发条件才会执行,如点击事件
watch用于观察Vue实例上数据的变动。一个对象。键是观察的表达式,值是对应的回调。值也可以是方法名,或者对象。
加载顺序
默认加载的时候先执行Computed-->watch,不执行method。当触发某一事件后,method-->watch、
computed&&method比较
<div id="app">
computed<br/>
{{fullName}}<br/>
{{fullName}}<br/>
Method<br/>
{{getfullName()}}<br/>
{{getfullName()}}<br/>
</div>
<script>
var app=new Vue({
el:"#app",
data:{
firstName:"wu",
lastName:"man",
fullName:""
},
computed:{
fullName:function(){
console.log("computed")
return this.firstName+" "+this.lastName;
}
},
method:{
console.log("method")
getfullName:function(){
return this.firstName+" "+this.lastName;
}
}
})
</script>
控制台输出:
computed
method
method
总结:多个{{}}使用了computed,computed内的function也只执行一次。仅当function内涉及到Vue实例绑定的data的值的改变,function才会重新执行,并修改DOM上的内容。methods则会多次调用。
computed&&watch比较:
<div id="app">
watch<br/>
{{fullName}}<br/>
{{fullName}}<br/>
</div>
<script>
var app=new Vue({
el:"#app",
data:{
firstName:"wu",
lastName:"man",
fullName:""
},
watch:{
firstName:function(val){
return this.fullName=val+" "+this.lastName ;
},
lastName:function(val){
return this.fullName=val+" "+this.firstName;
}
}
})
</script>
<div id="app">
computed<br/>
{{fullName}}<br/>
{{fullName}}<br/>
</div>
<script>
var app=new Vue({
el:"#app",
data:{
firstName:"wu",
lastName:"man",
},
computed:{
fullName:function(){
console.log("computed")
return this.firstName+" "+this.lastName;
}
})
</script>