Simple Vue.js Computed Properties Clarification

爱⌒轻易说出口 提交于 2019-12-10 16:19:35

问题


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:

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.


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?


回答1:


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
    }
  }
}

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)

demo



来源:https://stackoverflow.com/questions/52458203/simple-vue-js-computed-properties-clarification

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!