1.计算属性
1.差值语法实现
<div id="app">
<input type="text" v-model="firstName">
<input type="text" v-model="lastName">
<!-- 1.使用插值计算 -->
<h1>{{firstName-lastName}}</h1>
<!-- 2.methods中函数方法计算 -->
<h1>{{func()}}</h1>
<h1>{{fullname}}</h1>
<select name="" id="" v-model="fullname">
<option value="0">江西省</option>
<option value="1">湖南省</option>
<option value="2">广东省</option>
</select>
<select name="" id="">
<option v-for="(item,index) of arr[fullname]" :key="index+item" value="index">{{item}}</option>
</select>
</div>
2. computed计算属性
规则:
1.使用已有的属性来计算不存在的属性
2.默认调用一次get
3.简写形式(函数)没有set方法,如果需要更改值必须使用对象写法,不能使用函数
4.原理使用了Object.defineproperty(目标对象,名称,{get(),set(value)})
3.watch监听属性
规则
1.监听已有的属性
2.immediate设置为true默认触发一次,false不会默认触发
3.handler(新值,旧值)函数,当监听值发生改变时就会触发handler函数
4.写法:第一种Vue实例中,第二种实例化vm.$watch("监听的属性",{})
5.watch默认监听一层,需要监听多级如对象中的值,需要添加深度监听deep:true
6.简写,只有handler函数,才可以简写。写法:监听的属性名(新值,旧值){}
watch:{
bool:{
immediate:false,
handler(newValue,oldValue){
console.log(newValue);
console.log(oldValue);
console.log(this);
if(newValue==true){
this.userName = "张三";
this.obj.id = 100;
}else{
this.userName = "李四";
this.obj.id = 99;
}
}
},
// obj:{
// immediate:false,
// deep:true,
// handler(newValue,oldValue){
// console.log(newValue);
// console.log(oldValue);
// }
// },
// bool(newValue,oldValue){
// console.log(newValue);
// console.log(oldValue);
// console.log(this);
// }
},
3.computed与watch
1.computed能做到的watch都可以,watch能做到的computed不一定能
2.被Vue实例管理的函数最好都使用普通函数,不被Vue实例管理的函数最好都使用箭头函数,