App 에서 부모를 거쳐 자식으로 data 를 전달한다고 하자. 그런데 부모의 역할이 그저
전달에만 그친다면 이를 간소화 시킬수 있다.
App 에서 provide() 하고
중간과정 부모에에서 props를 정의하는 부분을 지워주고
실제 출력하는 자식에서 inject: [] 한다.
// App.vue
<template>
<button @click="message = 'Good?'">
Click!
</button>
<h1>App: {{ message }}</h1>
<Parent />
</template>
<script>
import Parent from "~/components/Parent"
export default {
components: {
Parent
},
data() {
return {
message: 'Hello world!!'
}
},
provide() {
return {
msg: this.message
}
}
}
// Parent.vue
<template>
<Child />
</template>
<script>
import Child from "~/components/Child"
export default {
components: {
Child
},
}
</script>
===========================================================================
// Child.vue
<template>
<div>
Child: {{ msg }}
</div>
</template>
<script>
export default {
inject: ['msg']
}
</script>
**주의!**
현재 Click! 을 눌러도 App 에서만 바뀌고 Child 에서는 바뀌지 않는다.
provide() 는 반응성을 제공하지 못한다.
데이터를 전달해서 한번 출력하는 용도 또는 반응성을 유지하게 하려면 추가작업을 해야한다.
// 추가 in script
import { computed } from 'vue'
computed: {
},
provide() {
return {
msg: computed(() => {
return this.message
})
}
}
vue 안에서 computed 기능을 가져와서 message 를 계산된 데이터로 만들어서 반환한다.