Vue: data Must Be A Function

ID

javascript.vue_data_must_be_function

Severity

high

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

JavaScript

Tags

reliability, vue

Description

Reports a Vue component option object whose data property is an object literal rather than a function. In Vue, every component instance must get its own copy of the reactive state; declaring data: { …​ } shares the same object across all instances of the component, which causes cross-instance state leaks the moment the component is reused.

Rationale

// Bad — every instance of `BadCounter` shares one `count`.
const BadCounter = {
  data: { count: 0 },
  template: "<div>{{ count }}</div>",
};

When the component is mounted twice on the same page, both copies share count. Incrementing one is observed by the other.

Remediation

Use the function form so each instance gets a fresh reactive state object:

// Good — `data()` shorthand.
const Good = {
  data() {
    return { count: 0 };
  },
};

// Good — arrow function form.
const GoodArrow = {
  data: () => ({ count: 0 }),
};

References