There are two components. I want to implement two-way data transmission between parent and child by providing a responsive object. However, I found that the object type can correctly implement responsiveness, but the basic data type cannot. Why?
My personal guess is that the optional API will trigger automatic unpacking for basic data types, but it will not be triggered in the setup function, thus causing inconsistency.
//parent
<script>
import Child from './Child.vue'
import { computed } from 'vue'
export default {
components: { Child },
data() {
return {
message: {"name":"hello"},flag:false
}
}, methods:{
change()
{
this.flag=!this.flag
}
},
provide() {
return {
message: this.message,flag:this.flag
}
}
}
</script>
<template>
<div>
<input v-model="message.name">
<button @change="change">click</button>
{{ flag}}
</div>
<Child />
</template>
//child
<script>
export default {
inject:["message","flag"],
methods:{
change()
{
this.flag=!this.flag
}
}
}
</script>
<template>
<div>
<input v-model="message.name">
<button @change="change">click</button>
{{ flag}}
</div>
</template>
Attempt: I consulted the official documentation and found that data() returns responsive objects, and basic data types can be passed correctly using the setup function.
Expected result: Bidirectional binding can be achieved when using optional provide to pass basic data types