vuejs3.0 从入门到精通——计算属性

计算属性

https://cn.vuejs.org/guide/essentials/computed.html

模板中的表达式虽然方便,但也只能用来做简单的操作。如果在模板中写太多逻辑,会让模板变得臃肿,难以维护。

比如说,我们有这样一个包含嵌套数组的对象:

js:

1
2
3
4
5
6
7
8
const author = reactive({
  name: 'John Doe',
  books: [
    'vue 2 - Advanced Guide',
    'vue 3 - Basic Guide',
    'vue 4 - The Mystery'
  ]
})

我们想根据author是否已有一些书籍来展示不同的信息:

template:

1
2
<p>Has published books:</p>
<span>{{ author.books.length > 0 ? 'Yes' : 'No' }}</span>

  这里的模板看起来有些复杂。我们必须认真看好一会儿才能明白它的计算依赖于author.books。更重要的是,如果在模板中需要不止一次这样的计算,我们可不想将这样的代码在模板里重复好多遍。

  我们看看使用计算属性来描述依赖响应状态的复杂逻辑:

vue:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<script setup>
import { reactive, computed } from 'vue'
 
const author = reactive({
  name: 'John Doe',
  books: [
    'vue 2 - Advanced Guide',
    'vue 3 - Basic Guide',
    'vue 4 - The Mystery'
  ]
})
 
// 一个计算属性 ref
const publishedBooksMessage = computed(() => {
  return author.books.length > 0 ? 'Yes' : 'No'
})
</script>
 
<template>
  <p>Has published books:</p>
  <span>{{ publishedBooksMessage }}</span>
</template>  

  我们在这里定义了一个计算属性publishedBooksMessagecomputed()方法期望接收一个 getter 函数,返回值为一个计算属性 ref。和其他一般的 ref 类似,你可以通过publishedBooksMessage.value访问计算结果。计算属性 ref 也会在模板中自动解包,因此在模板表达式中引用时无需添加.value

  vue 的计算属性会自动追踪响应式依赖。它会检测到publishedBooksMessage依赖于author.books,所以当author.books改变时,任何依赖于publishedBooksMessage的绑定都会同时更新。

  计算属性不是方法,不用加 (),你可以像普通属性一样将数据绑定到模板中的静态属性。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<script lang="ts">
export default{
    data(){
        return {
            message: "计算属性缓存 vs 方法",
            num: 0
        };
    },
 
    computed:{
      //计算属性的 getter
      reverseMessage: function(){
        //这里的 this 指向的是 vm 实例
        return this.message.split('').reverse().join()
      }
         
    },
    methods: {
 
    },
};
</script>
 
<template>
    <div class="about">
      <h1>This is an 计算属性缓存 vs 方法 page</h1>
      <p>反转后的操作结果</p>
      <h1>{{ reverseMessage }}</h1>
    </div>
  </template>
   
  <style>
  @media (min-width: 1024px) {
    .about {
      min-height: 100vh;
      display: flex;
      align-items: center;
    }
  }
  </style>
posted @   左扬  阅读(55)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
levels of contents
点击右上角即可分享
微信分享提示