简单的 Vue.js 计算属性说明 [英] Simple Vue.js Computed Properties Clarification

查看:23
本文介绍了简单的 Vue.js 计算属性说明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Vue.js 并不陌生,但我正在再次浏览文档,试图找出我第一次错过的任何内容.我在使用计算属性的基本示例部分中看到了这个声明:

I'm not new to Vue.js, but I'm going through the docs again, trying to pick up on anything I missed the first time. I came across this statement in basic example section of using computed properties:

您可以像普通属性一样将数据绑定到模板中的计算属性.Vue 知道 vm.reversedMessage 依赖于 vm.message,所以它会在 时更新任何依赖于 vm.reversedMessage 的绑定vm.message 变化.最好的部分是我们以声明方式创建了这种依赖关系:计算得到的 getter 函数没有副作用,这使得它更易于测试和理解.

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 函数没有副作用,我不清楚.我确实理解副作用是发生的一些与函数的纯意图没有直接关系的动作,但我不清楚它在这个语句中是如何使用的.


The part about we’ve created this dependency relationship declaratively: the computed getter function has no side effects, isn't clear to me. I do understand that a side effect is some action happening that is not directly related to the pure intentions of the function, but I'm not clear how it's being used in this statement.

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

Could someone explain further what the opposite could be? What are the potential side effects that could be happening?

推荐答案

这里的术语副作用是指在计算属性 getter 中执行的任何数据更改.例如:

The term side effect here refers to any data mutations performed in the computed property getter. For example:

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 生成的项目),您会看到 警告:

Notice how fullName mutates firstName, and reversedArray mutates array. If using ESLint (e.g., from 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)

演示

这篇关于简单的 Vue.js 计算属性说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆