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>
<style>
* {
margin-top: 10px;
}
</style>
<!-- 引入vue-->
<script type="text/javascript" src="/excise/src/vue2.0/daima/js/vue.js"></script>
</head>
<body>
<!--准备一个容器-->
<div id="root">
姓:<input type="text" value="张" v-model="firstName"><br/>
名:<input type="text" value="三" v-model="lastName">
<h3>全名:{{fullName}}</h3>
</div>
<script type="text/javascript">
Vue.config.productionTip = false //阻止vue在启动时生成提示
const vm = new Vue({
el: "#root",
data: {
firstName: "张",
lastName: "三"
},
computed: {
//完整写法
/* fullName: {
//get有什么作用?当有人读取fullName时,get就会被调用,且返回值就作为fullName的值
//get什么时候调用 ?1.初次读取fullName时 2.所依赖的数据发生变化时
get() {
console.log('get被调用了')
// console.log(this) //此处的this就是vm
return this.firstName + "-" + this.lastName;
},
//set什么时候调用 ? 当fullName被修改时(只读不改时,可不写set)
set(value) {
console.log('set', value)
const arr = value.split('-')
this.firstName = arr[0]
this.lastName = arr[1]
}
}*/
//简写 不写set,fullName相当于get,不能修改属性的值
fullName() {
console.log('get被调用了')
// console.log(this) //此处的this就是vm
return this.firstName + "-" + this.lastName;
}
}
})
</script>
</body>
</html>