什么是计算属性
解决模板中复杂的逻辑运算及复用问题
计算属性只在内部逻辑依赖的数据发生变化的时候才会被再次调用,它会缓存其依赖的上一次计算出的数据结果
多次复用一个相同值的数据,计算属性只调用一次
直接把计算属性的结果挂载到 vm 上
const App = {data() {return {studentCount: 1}},/** 1. 模板逻辑样式尽可能的绝对分离* 2. 逻辑运算结果需要被复用*//*template: `<h1>{{ studentCount > 0 ? ('学生数:' + studentCount) : '暂无学生' }}</h1><h2>{{ studentCount > 0 ? ('学生数:' + studentCount) : '暂无学生' }}</h2>`,*/template: `<h1>{{ studentCountInfo }}</h1><h2>{{ studentCountInfo }}</h2>`,computed: {studentCountInfo () {console.log('Invoked');return this.studentCount > 0? ('学生数:' + this.studentCount): '暂无学生'}}}const vm = Vue.createApp(App).mount('#app');
默认 function 是对应 getter
可以用对象显式定义 getter 和 setter 的方法
{data() {return {test: 123}},computed: {a() {return this.test;},b: {get() {return this.test * 2;},set(newValue) {this.test = newValue + 1;}}}}
应用场景
- 模板逻辑样式尽可能的绝对分离
 - 逻辑运算结果需要被复用
 
