Vue 的 `computed` 属性:介绍与使用

194 阅读2分钟

简介

在 Vue 中,computed 属性用于声明依赖其他数据而变化的数据。与 methods 不同,computed 属性会被缓存,只有当依赖的数据发生变化时才会重新计算。

在 Vue 2.x 中的使用

在 Vue 2.x 中,你可以在 Vue 组件的选项对象里定义 computed 属性。

new Vue({
  data: {
    a: 1,
    b: 2
  },
  computed: {
    sum: function() {
      return this.a + this.b;
    }
  }
})

你也可以用 getset 函数来创建一个可读写的计算属性。

new Vue({
  data: {
    firstName: 'John',
    lastName: 'Doe'
  },
  computed: {
    fullName: {
      get: function() {
        return `${this.firstName} ${this.lastName}`;
      },
      set: function(newValue) {
        const names = newValue.split(' ');
        this.firstName = names[0];
        this.lastName = names[names.length - 1];
      }
    }
  }
})

在 Vue 3.x 中的使用

在 Vue 3 中,computed 可以用在 setup 函数中,使其能与 Composition API 一同使用。

import { ref, computed } from 'vue';

export default {
  setup() {
    const a = ref(1);
    const b = ref(2);

    const sum = computed(() => {
      return a.value + b.value;
    });

    return {
      a,
      b,
      sum
    };
  }
}

主要特点

  • 缓存性: 只有当依赖数据改变时才会重新计算。
  • 响应性: 自动追踪其依赖的响应式数据。
  • 灵活性: 可以定义 getset 方法来创建可读写的计算属性。

使用场景

  • 性能优化: 当有高开销操作依赖多个数据源时。
  • 逻辑复用: 当多个地方需要用到相同的逻辑时。
  • 代码组织: 可以清晰地分离出响应式逻辑,使代码更易读、易维护。

注意事项

  • 避免在 computed 属性中执行副作用。这应该在 watch 或生命周期钩子中进行。

总结

computed 属性是 Vue 中非常强大的一项特性,无论是在 Vue 2.x 还是 Vue 3.x 中都发挥着重要的作用。合理使用 computed 属性可以极大地提高代码质量和性能。

希望这篇文章能帮助你更好地理解和使用 Vue 中的 computed 属性。如有进一步的疑问或需要更详细的解释,随时提出。