1、需要的属性不存在,需要通过已有的属性来计算得到

2、原理是借助了object.defineproperty方法提供的getter和setter

3、get函数什么时候执行:
(1)首次读取时候执行1次
(2)当以来的数据发生改变的时候,会再次被调用

4、与methods实现相比,内部有缓存机制,效率更高,调试更方便
5、备注:
(1)计算属性后最终会出现在vm上,允许直接读取

(2)如果计算属性要被修改,必须写set函数来响应修改,并且set函数中要引起计算式以来的数据发生

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>demo1.html</title>
<link rel="stylesheet" href="static/css/bootstrap.css">
<!-- 导入vue文件 -->
<script src="static/js/vue.js"></script>
<script src="static/js/vue-router.js"></script>
</head>
<body class="container">
<div id="app">
<!--
1、需要的属性不存在,需要通过已有的属性来计算得到
2、原理是借助了object.defineproperty方法提供的getter和setter
3、get函数什么时候执行:
(1)首次读取时候执行1次
(2)当以来的数据发生改变的时候,会再次被调用
4、好处:与methods实现相比,内部有缓存机制,效率更高,调试更方便
5、备注:
(1)计算属性后最终会出现在vm上,允许直接读取
(2)如果计算属性要被修改,必须写set函数来响应修改,并且set函数中要引起计算式以来的数据发生
-->
<p><a class="btn btn-block btn-primary" href="./demo1.html">计算属性示例</a></p>
<pre v-html="getFullName()"></pre>
<div class="form-group">
<label>username</label>
<input type="text" class="form-control" v-model="Username">
</div>
<div class="form-group">
<label>say</label>
<input type="text" class="form-control" v-model="Say">
</div>
<pre v-text="UserSay"></pre>
</div>
<script>
Vue.config.productionTip = false
const vm = new Vue({
el: "#app",
data: {
Username: "Goer",
Say: "php是世界上最好的语言",
},
methods: {
getFullName: function (e) {
return "张无忌"
}
},
computed: {
UserSay: {
get() {
console.log("get被调用了!")
return this.Username + " 说: " + this.Say
},
set(value) {
console.log("set被调用了,值是:", value)
}
}
}
})
</script>
</body>
</html>