简单 Vue.js 计算属性说明

Simple Vue.js Computed Properties Clarification

我不是 Vue.js 的新手,但我正在重新阅读文档,试图找出我第一次错过的任何内容。我在 basic example section of using computed properties:

中看到了这个声明

You can data-bind to computed properties in templates just like a normal property. Vue is aware that vm.reversedMessage depends on vm.message, so it will update any bindings that depend on vm.reversedMessage when vm.message changes. And the best part is that we’ve created this dependency relationship declaratively: the computed getter function has no side effects, which makes it easier to test and understand.


关于 我们以声明方式创建此依赖关系的部分:计算的 getter 函数没有副作用 ,我不清楚。我知道副作用是发生的一些与函数的纯意图没有直接关系的动作,但我不清楚它是如何在这个声明中使用的。

有人可以进一步解释相反的情况吗?可能发生的潜在副作用是什么?

此处的术语副作用指的是在计算属性getter中执行的任何数据突变。例如:

export default {
  data() {
    return {
      firstName: 'john',
      lastName: 'doe',
      array: [1,2,3]
    }
  },
  computed: {
    fullName() {
      this.firstName = 'jane'; // SIDE EFFECT - mutates a data property
      return `${this.firstName} ${this.lastName}`
    },
    reversedArray() {
      return this.array.reverse(); // SIDE EFFECT - mutates a data property
    }
  }
}

注意 fullName 如何突变 firstName,以及 reversedArray 如何突变 array。如果使用 ESLint(例如,来自 Vue CLI generated project), you'd see a warning:

[eslint] Unexpected side effect in "fullName" computed property. (vue/no-side-effects-in-computed-properties)
[eslint] Unexpected side effect in "reversedArray" computed property. (vue/no-side-effects-in-computed-properties)

demo