🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
>[success] # computed -- 计算属性 1. 在 `computed `中,可以定义一些 属性,这些属性,叫做 【计算属性】,类型`{ [key: string]: Function | { get: Function, set: Function } }`,下面这种情况就可以使用计算属性 ~~~ <span>{{ author.books.length > 0 ? 'Yes' : 'No' }}</span> ~~~ 2. 当给`v-model` 绑定计算属性的时候,注意这时候我们想做的是既可以赋值,又可以得到值,但是`computed`默认只能得到值也就是`get`,需要手动添加`set`方法 ~~~ export default { data() { return { firstName: 'John', lastName: 'Doe' } }, computed: { fullName: { // getter get() { return this.firstName + ' ' + this.lastName }, // setter set(newValue) { // 注意:我们这里使用的是解构赋值语法 [this.firstName, this.lastName] = newValue.split(' ') } } } } ~~~ 3. 计算属性的求值结果,会被缓存起来,方便下次直接使用; 如果 计算属性方法中,所以来的任何数据,都没有发生过变化,则,不会重新对 计算属性求值; 4. **不要在 getter 中做异步请求或者更改 DOM** 5. 源码对`setter`和`getter`处理 ![](https://img.kancloud.cn/21/bb/21bb8b18e402a1dd2cbc529f14e7fbc6_784x495.png) >[danger] ##### 案例 计算属性会基于它们的依赖关系进行缓存,在数据不发生变化时,计算属性是不需要重新计算的,是如果依赖的数据发生变化,在使用时,计算属性依然会重新进行计算,但`method`调用就算,如果大量使用对属性的重新赋值的地方会**消耗性能** ![](https://img.kancloud.cn/ff/9e/ff9ed5e388a64493c11bd5c6515d2df4_284x84.png) ~~~ <html lang="en"> <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>Document</title> </head> <body> <div id="app"> <!-- 1.methods --> <h2>{{ getFullName() }}</h2> <h2>{{ getFullName() }}</h2> <h2>{{ getFullName() }}</h2> <!-- 2.computed --> <h2>{{ fullName }}</h2> <h2>{{ fullName }}</h2> <h2>{{ fullName }}</h2> <!-- 修改Name值 --> <button @click="changeLastName">修改lastName</button> </div> <script src="https://unpkg.com/vue@next"></script> <script> // 1.创建app const app = Vue.createApp({ // data: option api data() { return { firstName: 'bbb', lastName: 'ccc', } }, methods: { getFullName() { console.log('getFullName-----') return this.firstName + ' ' + this.lastName }, changeLastName() { this.lastName = 'aaa' }, }, computed: { fullName() { console.log('computed fullName-----') return this.firstName + ' ' + this.lastName }, }, }) // 2.挂载app app.mount('#app') </script> </body> </html> ~~~ >[info] ## 官方文档 [文档位置](https://cn.vuejs.org/guide/essentials/computed.html#basic-example)