The data function of a Vue component should return a newly created object

  • VUE_SHARED_DATA
  • Error
  • Medium
  • vue

This rule applies when the data function of a Vue component returns a shared object.

Because a Vue component is reused for multiple instances, the returned data object should be a newly created one.
Otherwise, updating the data object of one instance will affect the data of all other instances, which can cause an unintended behavior.

Noncompliant Code Example

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

var obj = {
  msg: 'hi'
};

Vue.component('hello', {
  data() {
    return obj; // VUE_SHARED_DATA alarm because 'obj' is a shared object.
  },
  props: ['myMsg'],
  methods: {
    handleClick() {
      this.msg = this.myMsg;
    }
  },
  template: '<div @click="handleClick">{{ msg }}</div>'
});

new Vue({
  el: '#app',
  template: '<div><hello myMsg="hi1" /><hello myMsg="hi2" /></div>'
});

Compliant Code Example

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

Vue.component('hello', {
  data() {
    return { msg: 'hi' };
  },
  props: ['myMsg'],
  methods: {
    handleClick() {
      this.msg = this.myMsg;
    }
  },
  template: '<div @click="handleClick">{{ msg }}</div>'
});

new Vue({
  el: '#app',
  template: '<div><hello myMsg="hi1" /><hello myMsg="hi2" /></div>'
});

Version

This rule was introduced in DeepScan 1.16.0-beta.

See