Why Vue Component data Must Be a Function, Not an Object
The article explains that while a Vue root instance can define its data as an object or a function, a component's data must be a function to avoid shared memory between instances, illustrating the issue with code examples and detailing Vue's option‑merge validation.
Instance and Component data definitions
In a Vue root instance, the data option can be an object or a function. Example code shows both forms:
const app = new Vue({
el: "#app",
// object format
data: {
type: "object format"
}
}); const app = new Vue({
el: "#app",
// function format
data() {
return {
type: "function format"
};
}
});For a component, the data option must be a function; defining it as an object triggers a warning:
Vue.component('comp', {
template: `<div>组件</div>`,
data: {
name: "我是一个组件"
}
});Difference between function and object for component data
When data is an object, all component instances share the same memory address. Modifying one instance changes the other:
function Component() {}
Component.prototype.data = {
name: '我是组件'
};
const componentA = new Component();
const componentB = new Component();
componentA.data.name = '我是组件A';
console.log(componentB.data.name); // 我是组件AUsing a function returns a fresh object for each instance, preventing data pollution:
function Component() {
this.data = this.data();
}
Component.prototype.data = function () {
return {
name: '我是组件'
};
};
const componentA = new Component();
const componentB = new Component();
console.log(componentB.data.name); // 我是组件
componentA.data.name = '我是组件A';
console.log(componentB.data.name); // 我是组件
console.log(componentA.data.name); // 我是组件AUnderlying mechanism
When a component is created, Vue merges options via mergeOptions. During this merge, the data option is validated; if it is not a function, Vue issues a warning because component data must be a factory function to avoid shared state.
Conclusion
The root instance can use an object or a function because it is a singleton and does not suffer from data sharing issues. Component instances, however, must define data as a function so that each instance receives its own independent data object, preventing unintended cross‑instance mutations.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Full-Stack Trendsetter
Latest articles, video tutorials, and open-source projects on React, Vue, Angular, Ionic, React Native, Node.js, Mini Programs, and other cutting-edge technologies. A community for sharing and discussing full-stack development trends.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
