Arrow function with this accesses should not be used as a Vue instance option

  • VUE_BAD_ARROW_FUNC
  • Error
  • Medium
  • vue

This rule applies when an arrow function with this accesses is used as a Vue instance option.

Vue automatically binds the following function-typed options when creating a Vue instance:

  1. Getter/setter functions of computed property
  2. Properties of methods, watch, data option
  3. render(), renderError(), extends options
  4. Lifecycle methods

However, arrow functions are always bound with the this object of the context at which the function is defined, and it cannot be changed afterwards.
Therefore, this object will not be bound with the Vue instance when arrow functions are used to define the above options.

To define the above options correctly, you can use normal function definition syntax instead of arrow functions.

Noncompliant Code Example

View with compliant examples side by side
import Vue from 'vue';

new Vue({
  el: '#app',
  data: { msg: 'hello' },
  computed: {
    foo: () => {
      // VUE_BAD_ARROW_FUNC alarm because 'foo' getter function of 'computed' property is defined with arrow function and has 'this' access.
      return this.msg + ' hi';
    },
    bar: {
      get: () => {
        // VUE_BAD_ARROW_FUNC alarm because 'bar' getter function of 'computed' property is defined with arrow function and has 'this' access.
        return this.msg + ' bar';
      }
    }
  },
  created: () => {
    // VUE_BAD_ARROW_FUNC alarm because 'created' lifecycle method is defined with arrow function and has 'this' access.
    this.msg += ' created';
  },
  template: '<div>{{ msg }} {{ foo }} {{ bar }}</div>'
});

Compliant Code Example

View with noncompliant examples side by side
import Vue from 'vue';

new Vue({
  el: '#app',
  data: { msg: 'hello' },
  computed: {
    foo() {
      return this.msg + ' hi';
    },
    bar: {
      get() {
        return this.msg + ' bar';
      }
    }
  },
  created: function () {
    this.msg += ' created';
  },
  template: '<div>{{ msg }} {{ foo }} {{ bar }}</div>'
});

Version

This rule was introduced in DeepScan 1.14.0-beta.

See