본문 바로가기
프론트엔드/Vue.js

컴포넌트 - Provide, Inject

by step 1 2021. 8. 4.
반응형

바로 밑에 자식 컴포넌트로 데이터를 넘겨줄 때에는 props 속성을 이용하여 사용할 수 있다.

조상 component에서 후손 component에서 데이터를 한번에 내보낼 때에는 provide 속성을 이용할 수 있다.

provide를 이용할 때에는 기본적으로 반응성을 제공하고 있지 않기 때문에 설정을 추가해 주어야 한다

후손 component 에서는 inject를 속성을 이용하여 데이터를 받는다.

 

수정전 코드

App.vue

<template>
  <Parent :msg="message" />
</template>

<script lang="ts">
import Parent from '~/components/Parent'
export default {
  components: {
    Parent
  },
  data(){
    return {
      message: 'Hello world!'  
    }
  }
}
</script>

component -> parents 코드

<template>
  <Child
    :msg="msg" />
</template>

<script>
   import Child from '~/components/Child'
  
  export default {
    components: {
      Child
    },
    
    props: {
      msg: {
         type: String,
         default: ''
      }
    }
  }
  
</script>

component -> Child 코드

<template>
  <div>
    {{ msg }}
  </div>
</template>

<script>
export default{
 props: {
   msg: {
     type: String,
     default: ''
   }
 } 
}
</script>

브라우저 확인

 

provide, inject를 이용한 코드

App..vue

<template>
  <!-- <Parent :msg="message" /> -->
  <button @click="message = 'Good?'">
    Click!!
  </button>
  <h1>App: {{ message }}</h1>
  <Parent />
</template>

<script lang="ts">
import Parent from '~/components/Parent'
import {computed} from 'vue'
export default {
  components: {
    Parent
  },
  data(){
    return {
      message: 'Hello world!'  
    }
  },
  provide() {
    return {
      // msg: this.message
      // msg: computed(() => {
      //   return this.message
      // })
      msg: computed(() => this.message)
    }
  }
}
</script>

 

Child.vue

<template>
  <div>
    Child: {{ msg.value }}
  </div>
</template>

<script>
export default{
//  props: {
//    msg: {
//      type: String,
//      default: ''
//    }
//  } 
  inject: ['msg']
}
</script>

Parent.vue

<template>
  <Child
    :msg="msg" />
</template>

<script>
   import Child from '~/components/Child'
  
  export default {
    components: {
      Child
    },
    
    props: {
      msg: {
         type: String,
         default: ''
      }
    }
  }
  
</script>
반응형

'프론트엔드 > Vue.js' 카테고리의 다른 글

컴포지션 API - 반응형 데이터  (0) 2021.08.05
컴포넌트 - Refs  (0) 2021.08.04
컴포넌트 - slot  (0) 2021.08.04
컴포넌트 - Emit  (0) 2021.08.04
컴포넌트 속성 상속  (0) 2021.08.04