props default value inconsistent behavior with vue 2
Version
3.2.31
Reproduction link
Steps to reproduce
Vue 3: https://stackblitz.com/edit/vue-erg87v?file=src%2FApp.vue
Vue 2: https://stackblitz.com/edit/vue2-vue-cli-mjakzv?file=src%2FApp.vue
In Vue 3:
- input
obj.name
, type 123 (obj.name: [] doesn't update ) - click first input, type anything to trigger child component update (obj.name update to obj.name: [123])
- input
str1
, error:proxy set handler returned false for property '"str1"'
In Vue 2:
- input
obj.name
, type 123 (obj.name: [] update to obj.name: [123]) - click first input, type anything to trigger child component update (obj.name: [123] doesn't update)
- input
str1
, warning:[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "str1"
What is expected?
Vue 2 behavior is more reasonable
What is actually happening?
above
A workaround (wrap prop default value with reactive
, ref
doen't work):
import { ref, reactive } from 'vue';
export default {
props: {
obj: {
type: Object,
default() {
return reactive({ name: '' });
},
},
},
};
https://stackblitz.com/edit/vue-wjiyzs?file=src%2Fcomponents%2FHelloWorld.vue
https://vuejs.org/guide/components/props.html#mutating-object-array-props
modify object or array props is allowed