조상 컴포넌트에서 후손 컴포넌트로 데이터를 내릴 때 자식 컴포넌트를 거치지 않고, provide를 전달, inject를 통해 받는다. 단, 반응성을 지니지 않아 조상 컴포넌트에서 데이터를 내릴 때 vue에서 import를 하여 msg: computed(() => this.message) 내보내면 반응성을 지니게 됩니다. 그리고 후손 컴포넌트에서 데이터를 받을 때는 msg.value로 받습니다.
조상 컴포넌트
<template>
<button @click="message = 'Good?'">
Click
</button>
<h1>App: {{ message }}</h1>
<Parent />
</template>
<script>
import Parent from '~/components/ParentComp'
import { computed } from 'vue'
export default {
components: {
Parent
},
data() {
return {
message: 'Hello world!'
}
},
provide() {
return {
msg: computed(() => this.message)
}
}
}
</script>
자식 컴포넌트
<template>
<Child />
</template>
<script>
import Child from "~/components/ChildComp";
export default {
components: {
Child
},
props: {
msg: {
type: String,
default: ''
}
}
}
</script>
후손 컴포넌트
<template>
<div>
Child: {{ msg.value }}
</div>
</template>
<script>
export default {
inject: [
'msg'
]
}
</script>