用三种方法: 计算属性、 方法、侦听器, 实现 fullName 的全部展示,以及修改对应的名字和年龄的时候, 对应的缓存机制。

1: 计算属性: (内置缓存机制)
当更改age的时候, fullName 函数不执行;
当更改fristName的时候, fullName 函数才执行
<div id = "app">
<span>{{fullName}}</span>
<span>{{age}}</span>
</div>
<script>
var vm = new Vue({
el : "#app",
data: {
fristName : "Christine",
lastName : "Gao",
age : "26"
},
// “计算属性” 实现: 具有缓存机制, 即改变年龄的时候, 执行 fullName 函数
computed : {
fullName : function () {
console.log("计算了一次");
return this.fristName + " " + this.lastName;
}
}
})
</script>

2、方法: (无内置缓存)
当更改age的时候, fullName 函数执行, 这样就增加了代码冗余,浏览器运行性能降低;
当更改fristName的时候, fullName 函数仍执行。
<div id = "app">
<span>{{fullName()}}</span>
<span>{{age}}</span>
</div>
<script>
var vm = new Vue({
el : "#app",
data: {
fristName : "Christine",
lastName : "Gao",
age : "26"
},
// “方法” 实现 : 改变年龄的时候, 也会执行 fullName 函数
methods : {
fullName : function () {
console.log("用方法,计算了一次")
return this.fristName + " " + this.lastName;
}
}
})
</script>

3、侦听器: (有内置缓存)
跟“计算属性”相似, 但是代码相较于“计算属性”而言, 比较繁琐且冗余。
<div id = "app">
<span>{{fullName}}</span>
<span>{{age}}</span>
</div>
<script>
var vm = new Vue({
el : "#app",
data: {
fristName : "Christine",
lastName : "Gao",
fullName : "Christine Gao",
age : "26"
},
// “侦听” 实现 :实现了缓存, 但是代码冗余。
watch : {
firstName : function () {
console.log("侦听实现 , 计算了一次");
this.fullName = this.fristName + " " + this.lastName;
},
lastName : function () {
console.log("侦听实现 , 计算了一次");
this.fullName = this.fristName + " " + this.lastName;
}
}
})
</script>

网友评论