JS.VUE.NO.SIDE.EFFECTS.IN.COMPUTED.PROPERTIES

Disallow side effects in computed properties

Rule Details

This rule is aimed at preventing the code which makes side effects in computed properties and functions.

It is considered a very bad practice to introduce side effects inside computed properties and functions. It makes the code not predictable and hard to understand.

{'vue/no-side-effects-in-computed-properties': ['error']}

Copy
<script>
/* GOOD */
export default {
  computed: {
    fullName () {
      return `${this.firstName} ${this.lastName}`
    },
    reversedArray () {
      return this.array.slice(0).reverse() // .slice makes a copy of the array, instead of mutating the orginal
    }
  }
}
</script>

{'vue/no-side-effects-in-computed-properties': ['error']}

Copy
<script>
/* BAD */
export default {
  computed: {
    fullName () {
      this.firstName = 'lorem' // <- side effect
      return `${this.firstName} ${this.lastName}`
    },
    reversedArray () {
      return this.array.reverse() // <- side effect - orginal array is being mutated
    }
  }
}
</script>

{'vue/no-side-effects-in-computed-properties': ['error']}

Copy
<script>
import {computed} from 'vue'
/* GOOD */
export default {
  setup() {
    const foo = useFoo()

    const fullName = computed(() => `${foo.firstName} ${foo.lastName}`)
    const reversedArray = computed(() => {
      return foo.array.slice(0).reverse() // .slice makes a copy of the array, instead of mutating the orginal
    })
  }
}
</script>

{'vue/no-side-effects-in-computed-properties': ['error']}

Copy
<script>
import {computed} from 'vue'
/* BAD */
export default {
  setup() {
    const foo = useFoo()

    const fullName = computed(() => {
      foo.firstName = 'lorem' // <- side effect
      return `${foo.firstName} ${foo.lastName}`
    })
    const reversedArray = computed(() => {
      return foo.array.reverse() // <- side effect - orginal array is being mutated
    })
  }
}
</script>

Options

Nothing.

Further Reading

  • Guide - Computed Caching vs Methods (https://v3.vuejs.org/guide/computed.html#computed-caching-vs-methods)

The content on this page is adapted from the ESLint User Guide. Copyright © OpenJS Foundation and other contributors, www.openjsf.org. All rights reserved. https://eslint.org/docs/rules/