App.vue에서 Parent.vue를 거쳐 Child.vue에 msg를 띄우는 방식, Props를 통해 데이터를 내려줬다.
App.vue
<template>
<Parent :msg="message" />
</template>
<script>
import Parent from '~/components/Parent'
export default {
components: {
Parent
},
data() {
return {
message: "Hello world"
}
},
}
</script>
<style>
</style>
Parent.vue
<template>
<Child :msg="msg" />
</template>
<script>
import Child from '~/components/Child'
export default {
components: {
Child
},
props: {
msg: {
type: String,
default: ''
}
}
}
</script>
<style>
</style>
Child.vue
<template>
<div>
{{ msg }}
</div>
</template>
<script>
export default {
props: {
msg: {
type: String,
default:''
}
}
}
</script>
<style>
</style>
이렇게 되면 Parent.vue
의 경우는 정말 아무 기능 없이 Prop의 기능만 하려고 중간다리 역할을 하는데 msg
의 정보를 모두 입력해서 넘겨줘야한다.
Parent.vue
를 중간다리 역할로 쓸 필요 없이 바로Child
로 쏴주는 기능
App.vue
<template>
<Parent />
</template>
<script>
import Parent from '~/components/Parent'
export default {
components: {
Parent
},
data() {
return {
message: "Hello world"
}
},
provide() {
return {
msg: this.message
}
}
}
</script>
<style>
</style>
Parent.vue
<template>
<Child />
</template>
<script>
import Child from '~/components/Child'
export default {
components: {
Child
},
}
</script>
<style>
</style>
Child.vue
<template>
<div>
Child: {{ msg }}
</div>
</template>
<script>
export default {
inject: ['msg']
}
</script>
<style>
</style>
provide
라는 개념을 통해 반응성을 유지해주는 데이터를 만들려면computed
라는 함수를 실행해서 그 내부에call back함수
를 만들어서 그 내에서 특정한 반응성을 가지고싶은 데이터를 반환해주면 된다.
App.vue
객체 구조분해로 vue라는 패키지를 가져옴
provide() msg
에computed
라는 함수를call back
으로 실행하게 되면 하나의 계산된 데이터를 만들고msg
로 들어가서 반환한다.
<template>
<button
@click="message='Good?'">
Click
</button>
<h1> App : {{ message }}</h1>
<Parent />
</template>
<script>
import Parent from '~/components/Parent'
import { computed } from 'vue'
export default {
components: {
Parent
},
data() {
return {
message: "Hello world"
}
},
provide() {
return {
msg: computed(() => {
return this.message
})
}
}
}
</script>
Chlid.vue
child부분에 제대로된 데이터를 출력하고 싶으면
그 안에있는value
속성을 사용,msg.value
<template>
<div>
Child: {{ msg.value }}
</div>
</template>
<script>
export default {
inject: ['msg']
}
</script>
동시에 두가지 message가 변경됨
원래는 데이터를 내려주기위해 props
을 해야하지만, 최대한 생략해주기 위해 provide로 전달 가능하다.
하지만 단점이 있다!!
전달되는 데이터는 반응성을 가지지 않는다. 즉, 조상부분에서 데이터를 변경하더라도 하위요소에 갱신할 수 있는 구조가 되지 않는다.
이걸 극복하기 위해 vue
라는 패키지에서 computed
라는 계산된 데이터를 가져와서 동작시키는 방법으로 해당하는 데이터의 반응성을 유지한 상태로 조상요소에서 후손요소로 데이터를 연결시켜줄 수 있는 구조를 만들어준다.