I want to change the value of message with provide, but it doesn't work in any way, I wonder where am I going wrong?
I looked through the provide inject event but couldn't figure it out.
App.vue
<script>
import Child from './Child.vue'
export default {
components: { Child },
data(){
message:false
},
provide() {
return {
fullMessage: this.message
}
}
}
</script>
<template>
<Child />
</template>
Child.vue
<script>
import GrandChild from './GrandChild.vue'
export default {
components: {
GrandChild
}
}
</script>
<template>
<GrandChild />
</template>
GrandChild.vue
<script>
export default {
inject: ['fullMessage'],
methods:{
handleStatus(){
this.fullMessage = !this.fullMessage
}
}
}
</script>
<template>
<p>essage to grand child: {{ fullMessage }}</p>
<button @click="handleStatus">
Status Change
</button>
</template>
CodePudding user response:
You can use ref or reactive to change provided value:
const { ref, provide, inject } = Vue
const app = Vue.createApp({
setup() {
const fullMessage = ref(false)
provide('fullMessage', fullMessage)
}
})
app.component('child', {
template: `
<grand-child></grand-child>
`
})
app.component('grandChild', {
template: `
<p>message to grand child: {{ fullMessage }}</p>
<button @click="handleStatus">
Status Change
</button>
`,
setup() {
const fullMessage = inject('fullMessage')
return {
fullMessage,
handleStatus: () => fullMessage.value = !fullMessage.value
}
},
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
<child></child>
</div>