computed用于解决模版中复杂的逻辑运算,或者逻辑需要被复用的地方。
// badconst App = {template: `<h1>{{ studentCount > 0 ? "学生数量:"+ studentCount : "暂无学生" }}</h1><h1>{{ studentCount > 0 ? "学生数量:"+ studentCount : "暂无学生" }}</h1>`,data() {return {studentCount: 1};},};
:::info
以上代码的问题有两个方面:
1、模版的逻辑和样式要尽可能的绝对分离,模版上不要做太多的逻辑。
2、如果另一个地方要显示同样的逻辑,这样就会导致需要运算两次。
:::
计算属性的特点
1、多次复用相同值的数据,计算属性只会调用一次
const App = {template: `<h1>{{ studentCountInfo }}</h1><h1>{{ studentCountInfo }}</h1>`,data() {return {studentCount: 1};},computed: {studentCountInfo() {// Invoked 只会被执行一次console.log("Invoked");return this.studentCount > 0 ? "学生数量:" + this.studentCount : "暂无学生";}}};const vm = createApp(App).mount("#app");
2、计算属性只会在内部逻辑依赖的数据发生变化的时候才会重新调用。
const App = {template: `<h1>{{ studentCountInfo }}</h1><h1>{{ studentCountInfo }}</h1><button @click="clickBtn">按钮</button><button @click="clickBtn2">按钮</button>`,data() {return {studentCount: 1};},computed: {studentCountInfo() {console.log("Invoked");return this.studentCount > 0 ? "学生数量:" + this.studentCount : "暂无学生";}},methods: {clickBtn() {this.studentCount = new Date();},clickBtn2() {this.studentCount = 2;}}};

3、计算属性会缓存其依赖的上一次计算出的数据结果
computed 和 methods 的区别
- 在使用时,
computed可以当做属性使用,而methods则可以当做方法调用。 computed可以具有getter和setter方法,因此可以赋值,而methods是不行的。const App = {// ...computed: {studentCountInfo() {console.log("Invoked");return this.studentCount > 0 ? "学生数量:" + this.studentCount : "暂无学生";},result: {get() {},set() {}}}}
computed无法接收多个参数,而methods可以。computed是有缓存的,而methods没有。computed属性会暴露到应用/组件的实例上。

