背景:想要实现将firstName和lastName拼接成fullName
实现的方法有三种,分别是:计算属性,方法与监听器。
1.计算属性:
<div id="app">
{{fullName}}
</div>
<script>
var vm = new Vue({
el:"#app",
data:{
firstName:"Dell",
lastName:"Lee",
},
computed:{
fullName:function(){
console.log("计算了一次");
return this.fisrtName + " " + this.lastName;
}
}
})
</script>
2.方法
<div id="app">
{{fullName()}}
</div>
<script>
var vm = new Vue({
el:"#app",
data:{
firstName:"Dell",
lastName:"Lee",
fullName:"Dell Lee"
},
methods:{
fullName: function(){
return this.fisrtName + " " + this.lastName;
}
}
})
</script>
3.监听器
<div id="app">
{{fullName}}
</div>
<script>
var vm = new Vue({
el:"#app",
data:{
firstName:"Dell",
lastName:"Lee",
fullName:"Dell Lee"
},
watch:{
firstName:function(){
console.log("计算了一次")
this.fullName = this.firstName + " " + this.lastName;
},
lastName:function(){
console.log("计算了一次")
this.fullName = this.firstName + " " + this.lastName;
}
}
})
</script>
综合起来看,当一个功能既可以使用计算属性又可以使用方法或者监听器时,最好使用计算属性来实现,比较简洁。