一、计算属性
computed
规则:
1.使用已有的属性来计算不存在的属性
2.默认调用一次get
3.简写形式(函数)没有set方法,如果需要更改值必须使用对象写法,不能使用函数
4.原理使用了Object.defineproperty(目标对象,名称,{get(),set(value)})
语法:
1.对象式 computed:{
属性名:{
get(){},
set(value){}
}
2.对象式 computed(value){}
get()执行时间
- 在初次运行时执行
- 当绑定的属性值发生变化时执行
实例
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<input v-model="a">
<input v-model="b">
<h1>{{c}}</h1>
<div>
</body>
<script src="./vue.js"></script>
<script>
Vue.config.productionTip = false;
var vm = new Vue({
el:"#app",
data() {
return {
a:"橙",
b:"子",
c:""
},
computed:{
fullname:{
get(){
console.log("调用了get方法");
return this.a+"-"this.b;
},
set(value){
console.log(value);
}
}
}
})
</script>
二、侦听属性
watch
watch监听属性
规则
1.监听已有的属性
2.immediate设置为true默认触发一次,false不会默认触发
3.handler(新值,旧值)函数,当监听值发生改变时就会触发handler函数
4.写法:第一种Vue实例中,第二种实例化vm.$watch(“监听的属性”,{})
5.watch默认监听一层,需要监听多级如对象中的值,需要添加深度监听 deep:true
6.简写,只有handler函数,才可以简写。写法:监听的属性名(新值,旧值){}
实例
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
<h2>{{userName}}</h2>
<h3>{{obj.id}}</h3>
<button @click="bool=!bool">点击改变值</button>
</div>
</body>
<script src="./vue.js"></script>
<script>
Vue.config.productionTip = false;
var vm = new Vue({
el:"#app",
data() {
return {
bool:true,
userName:"",
obj:{
id:99
}
},
//局部式
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;
}
}
}
})
//全局式
vm.$watch("userName",function(newValue,oldValue){
console.log("---------------------");
console.log(newValue);
console.log(oldValue);
console.log(this);
})
</script>