<div id="app">
<div>{{fullName}}</div>
</div>
<script>
var vm = new Vue({
el: "#app",
data: {
name: "<h1>Dell</h1>",
firstName: "sheng",
lastName: "jun yong",
age: 28
},
// 方式一:
// 调用一次,执行一次,data数据更新页面重新渲染,该方法又会被调用,性能不佳
methods: {
// fullName: function(){
// return this.firstName + this.lastName
// }
},
// 方式二
// 计算属性有缓存,第一次调用执行一次,只要与其相关属性不变,多次调用只会执行一次方法,节约性能
computed: {
// 调用{{fullName}}无需括号,fullName相当于一个属性this.fullName,该方法的返回值就是属性值
fullName() {
return this.firstName + this.lastName
}
},
// 方式三
watch: {
// 监听firstName数据,当firstName变化,该方法被回调
firstName(){
console.log("监听firstName")
this.fullName = this.firstName + this.lastName
},
// 监听lastName数据,当lastName变化,该方法被回调
lastName(){
console.log("监听lastName")
this.fullName = this.firstName + this.lastName
}
}
})
</script>
原文:https://www.cnblogs.com/shengjunyong/p/12150222.html