<!--计算属性:1. 定义:要用的属性不存在,要通过已有的属性计算得来2. 原理:底层借助了 Object.defineProperty 方法提供的 getter 和 setter3. get 函数什么时候执行?(1). 初次读取时会执行一次(2). 当依赖的数据发生改变时会被再次调用4. 优势:与 methods 实现相比,内部有缓存机制(复用),效率高,调试方便5. 备注:1. 计算属性最终会出现在 vm 上,直接读取使用即可2. 如果计算属性要被修改,那必须写在 set 函数去响应修改,且 set 中要引起计算时依赖的数据发生改变
-->
<div id="root"><ul><li>姓:<input type="text" v-model="firstName"></li><li>名:<input type="text" v-model="lastName"></li><li>全名:{{getFullName}}</li><li>全名:{{getFullName}}</li><li>全名:{{getFullName}}</li><li>全名:{{getFullName}}</li><li>全名:{{getFullName}}</li><li>全名:{{getFullName}}</li><li>全名:{{getFullName}}</li></ul>
</div>
<script src="../js/vue.js"></script>
<script>Vue.config.productionTip = false;const vm = new Vue({el: '#root',data: {firstName: '张',lastName: '三'},computed: {getFullName: {get() {console.log(1);console.log('已通过 get 方式获取到了 getFullName 这个计算属性的值');return this.firstName + ' - ' + this.lastName;},set(value) {console.log('已通过 set 方式修改了 getFullName 这个计算属性的值');let arr = value.split('-');this.firstName = arr[0];this.lastName = arr[1];}}}});
</script>
<script src="../js/vue.js"></script>
<script>Vue.config.productionTip = false;const vm = new Vue({el: '#root',data: {firstName: '张',lastName: '三'},computed: {getFullName: {get() {console.log(1);console.log('已通过 get 方式获取到了 getFullName 这个计算属性的值');return this.firstName + ' - ' + this.lastName;},set(value) {console.log('已通过 set 方式修改了 getFullName 这个计算属性的值');let arr = value.split('-');this.firstName = arr[0];this.lastName = arr[1];}}}});
</script>
Vue 计算属性的简写
computed: {// 原来的写法getFullName: {get() {console.log(1);console.log('已通过 get 方式获取到了 getFullName 这个计算属性的值');return this.firstName + ' - ' + this.lastName;},set(value) {console.log('已通过 set 方式修改了 getFullName 这个计算属性的值');let arr = value.split('-');this.firstName = arr[0];this.lastName = arr[1];}}// 如果只是读取(getter), 就可以写成这种形式getFullName() {console.log('get 被调用了');return this.firstName + '-' + this.lastName;}
}