Provide(제공) / Inject(주입)

eg( 사진으로 보면 한눈에 알수있다. 데이터를 특정 컴포넌트까지 바로 전달가능하다 )


- 부모템플릿에서 자식의 자식의 자식까지 전달할 props를 불필요하게 설정할 필요가 없음 (진작 알았다면..)

- 반응성을 가진 변수를 전달시 전달 받은 후에도 그대로 반응성을 가짐


부모 템플릿

<script setup>
import { ref, provide } from 'vue'
import Child from './Child.vue'

// ref를 제공함으로써 손자컴포넌트는
// 여기서 일어나는 변화에 반응할 수 있습니다.
const message = ref('안녕')
provide('message', message)
</script>

<template>
  <input v-model="message">
  <Child />
</template>


자식컴포넌트

<script setup>
import GrandChild from './GrandChild.vue'
</script>

<template>
  <GrandChild />
</template>


손자컴포넌트

<script setup>
import { inject } from 'vue'

const message = inject('message')
function changeMessage(){
  message.value="클릭해서 메세지 변경했어요"
}
</script>

<template>
  <p> 손자에게 전하는 메시지: {{ message }} </p>
  <button v-on:click="changeMessage">손자컴포넌트에서 메세지 변경</button>
</template>


실제 사용 사례

eg



참조

실제예제

공식문서

May 18, 2024 Views 59