Vue2中props数组默认值为何用()=>[]而非直接[]?
default: () => [] in Vue Props Great question! Let's break this down clearly:
First, what does default: () => [] do?
This line sets a default value for the items prop. When the parent component doesn’t pass the items prop, or passes an invalid value, this prop will automatically use the empty array returned by the arrow function.
Now, why use an arrow function to return an empty array instead of just writing default: []? There are two critical reasons:
1. Prevent shared reference bugs with reference types
Arrays (and objects) are reference types in JavaScript. That means if you assign them directly as a default value, every instance of your Vue component will share the exact same underlying array in memory.
For example, if you wrote default: [] directly, and one component instance modifies this array (like this.items.push('new item')), every other instance using the default value would see that change too. This leads to unexpected cross-component state leaks that are hard to debug.
By using () => [], every time a component instance is created, the arrow function runs and returns a new, fresh empty array. Each instance gets its own independent copy, so modifications to one don’t affect others.
2. It follows Vue’s official guidelines
Vue’s documentation explicitly requires using a factory function (like this arrow function) to return default values for reference type props (arrays, objects). This enforces the "unique copy per instance" behavior, which is the safe and expected behavior for component props.
A quick example to show the difference
Suppose you had this flawed prop setup:
props: { items: { type: Array, required: false, default: [] // ❌ Shared array across all instances } }
And in your component:
mounted() { this.items.push('Hello') }
If you render 3 instances of this component without passing items, all 3 would have ['Hello'] in their items prop—they’re sharing the same array.
With default: () => [], each instance gets a new array, so only the instance that runs push would have the added item.
内容的提问来源于stack exchange,提问作者theMaertin




