The array passed after using defineMdel will lose its responsiveness
Vue version
3.4.7
Link to minimal reproduction
Steps to reproduce
Step 1: Create an empty array, Step 2: Use defineModel to pass to child components, Step 3: Then after the subcomponent performs data operations, Step 4: The parent component displays the data
What is expected?
Display the data after operation
What is actually happening?
Displayed as empty array
System Info
No response
Any additional comments?
The official website recommends using defineModel after 3.4, but the test found that the data cannot be displayed. Using controlled experiments, we found that props transfer can successfully display correct data.
After testing, it was found that if the array is not cleared when clicking, the data can be displaye d correctly.
In reality, after assigning foo.value = []
, the updated value of foo.value
can only be accessed in the child component after the next execution of the render function. Therefore, when you use foo.value.push({/**/})
, you are actually pushing onto the old foo.value
rather than the new one. After the child component is updated, foo.value
will have the new value, which is an empty array. You should perform the assignment after the push
operation, once the child component update is complete.
const foo = defineModel('foo', {
required: true
})
const handleDefineModelPushClick = () => {
const arr = []
arr.push({ key: 'use defineModel' })
foo.value = arr
}
When you keep in mind that defineModel()
is a convenience shortcut for the following, it becomes more appearant:
const props = defineProps(['modelValue'])
const emits = defineEmits(['update:modelValue'])
// you basically did this:
emit('update:modelValue', [])
props.modelValue.push(....)
In reality, after assigning
foo.value = []
, the updated value offoo.value
can only be accessed in the child component after the next execution of the render function. Therefore, when you usefoo.value.push({/**/})
, you are actually pushing onto the oldfoo.value
rather than the new one. After the child component is updated,foo.value
will have the new value, which is an empty array. You should perform the assignment after thepush
operation, once the child component update is complete.const foo = defineModel('foo', { required: true }) const handleDefineModelPushClick = () => { const arr = [] arr.push({ key: 'use defineModel' }) foo.value = arr }
感谢