<body>
<div id="app">
<h2>{{watchFullName}}</h2>
<!-- methods即使firstName与lastName没有改变,也会再次执行 -->
<h2>{{getFullName()}}</h2>
<h2>{{getFullName()}}</h2>
<h2>{{getFullName()}}</h2>
<!-- computed,计算属性有缓存,只有关联属性改变才会再次执行 -->
<h2>{{fullName}}</h2>
<h2>{{fullName}}</h2>
<h2>{{fullName}}</h2>
<!-- 非关联属性 -->
<p>{{age}}</p>
</div>
<script>
const app = new Vue({
el: "#app",
data() {
return {
firstName: "天线",
lastName: "宝宝",
age: 18,
watchFullName:"海绵宝宝"
}
},
methods: {
getFullName() {
console.log("你调用了getFullName方法");
return this.firstName + "" + this.lastName;
},
change(){
return this.watchFullName = "1111";
}
},
computed: {
fullName() {
console.log("你调用了fullName属性");
return this.firstName + "" + this.lastName;
}
},
watch:{
//第一种
firstName(newval,oldval){
console.log(newval);
console.log(oldval);
this.watchFullName = "刘备"
}
//第二种
/* firstName:{
handler:function(newval,oldval){
console.log(newval);
console.log(oldval);
this.watchFullName = "关羽"
},
immediate:true,//立即监听
},
watchFullName:"change" */
}
})
//第三种
/* app.$watch('firstName',(newval,oldval)=>{
console.log(newval);
console.log(oldval);
}) */
</script>
</body>
监视属性顾名思义只能监视属性,不能监视方法,需要注意计算属性也是属性。