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
<template>
  <div @click="handleClick">{{ msg }}</div>
</template>

<script>
var obj = {
  msg: 'hi'
};
export default {
  data() {
    return obj; // VUE_SHARED_DATA alarm because 'obj' is a shared object.
  },
  props: ['myMsg'],
  methods: {
    handleClick() {
      this.msg = this.myMsg;
    }
  }
}
</script>

Compliant Code Example

View with noncompliant examples side by side
<template>
  <div @click="handleClick">{{ msg }}</div>
</template>

<script>
export default {
  data() {
    return { msg: 'hi' };
  },
  props: ['myMsg'],
  methods: {
    handleClick() {
      this.msg = this.myMsg;
    }
  }
}
</script>

Version

This rule was introduced in DeepScan 1.16.0-beta.

See

Was this documentation helpful?