Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Vue.js Computed Properties Clarification

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?

like image 966
qarthandso Avatar asked Sep 22 '18 15:09

qarthandso


1 Answers

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

like image 132
tony19 Avatar answered Oct 13 '22 01:10

tony19