计算属性:
1.定义:要用的属性不存在,要通过自己计算得来。
2.原理:底层借助了Object.defineProperty方法提供的getter和setter。
3.get函数什么时候调用?
(1)初次读取时会执行一次;
(2)当依赖的数据发生变化时会被再次调用。
4.优势:与methods实现相比,内部有缓存机制(复用),效率更高,调试方便
5.备注:
(1).计算属性最终会出现在vm上,直接读取即可;
(2).如果计算属性要被修改,那必须写set函数去响应修改,且set中要引起计算时依赖的数据发生改变。
示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>计算属性</title>
<!--引入Vue-->
<script src="../lib/vue.js"></script>
<link rel="stylesheet" href="../../鼠标指针样式.css"/>
</head>
<body>
<!--准备好一个容器-->
<div id="root">
姓名:<input type="text" v-model="name"/><br/><br/>
年龄:<input type="text" v-model="age"/><br/><br/>
你是:<span>{{name}},今年{{age}}岁</span><!--使用插值语法实现--><br/><br/>
你是:<span>{{showInfo()}}</span><!--使用函数实现--><br/><br/>
你是:<span>{{info}}</span><!--使用计算属性实现-->
</div>
<script type="text/javascript">
Vue.config.productionTip = false;
const vm = new Vue({
el:'#root',
data:{
name:'retrace',
age:21
},
methods:{
showInfo(){//此处的this是vm
console.log("----->showInfo");
return this.name + ",今年" + this.age + "岁";
}
},
computed:{
//完整写法 可以读写
/*info:{
//get作用:当有人读取info时,get就会被调用,且返回值就作为info的值
//get什么时候调用?1.初次读取info时;2.所依赖的数据发生变化时。
get(){//此处的this是vm
console.log('info get被调用了');
return this.name + ",今年" + this.age + "岁";
},
//set什么时候调用?当info被修改时
set(value){
console.log('info set被调用了');
const arr = value.split(',');
this.name = arr[0];
this.age = arr[1];
}
}*/
//简写 只读
info(){
console.log('info get被调用了');
return this.name + ",今年" + this.age + "岁";
}
}
});
</script>
</body>
</html>