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

计算属性

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

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

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

js:

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

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

template:

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

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

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

vue:

<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的绑定都会同时更新。

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

<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 @ 2023-02-04 19:15  左扬  阅读(41)  评论(0编辑  收藏  举报
levels of contents