꾸준히 성장하는 개발자

[Vue.js] Provide , Inject 본문

Vue.js

[Vue.js] Provide , Inject

ahleum 2023. 1. 3. 16:07

 

이런 구조의 component에서 데이터를 전달할 때 

 

아래는 

App.vue에 있는 data를 Child.vue에서 출력해주기 위해 props로 전달해주는 과정이다

// App.vue

<template>
  <div id="app">
    <parent :msg="message" />
  </div>
</template>

<script>
import Parent from "@/components/Parent.vue";

export default {
  name: "App",
  components: { Parent },

  data() {
    return {
      message: "hello world",
    };
  },
};
</script>
<style scoped></style>

props로 전달을 하게 되면 App.vue에서 Child.vue로 도달하기 위해서는 

어쩔 수 없이 중간단계인 Parent.vue를 거쳐야 한다.

Parent.vue에서는 msg라는 data가 필요하지도 않은데 props로 받고 있는 것 

// Parent.vue

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

<script>
import Child from "@/components/ChildVue.vue";

export default {
  name: "Parent",
  components: { Child },
  props: {
    msg: {
      type: String,
      default: "",
    },
  },
};
</script>
// Child.vue

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

<script>
export default {
  name: "ChildVue",
  props: {
    msg: {
      type: String,
      default: "",
    }
  },
};
</script>

 

 

이런 위의 불편한 부분을 provide, inject를 이용하여 개선하는 방법

 

 

 

// App.vue

<template>
  <div id="app">
    <parent />    // props로 사용하던부분도 삭제해준다
  </div>
</template>

<script>
import Parent from "@/components/Parent.vue";

export default {
  name: "App",
  components: { Parent },

  data() {
    return {
      message: "hello world",
    };
  },
  provide() {                   // 이렇게 provide로 메서드로 전달해준다.
    return {
      msg: this.message,        // 현재 msg로 전달을 해주고 있기 때문에 child에서도 msg로 사용해야한다
    };
  },
};
</script>
// Parent.vue

<template>
  <Child  />  // :msg="msg" props로 전해주던 부분을 지워준다
</template>

<script>
import Child from "@/components/ChildVue.vue";

export default {
  name: "Parent",
  components: { Child },
//  props: {                     props로 전해주던 부분을 지워준다
//    msg: {
//      type: String,
//      default: "",
//    },
//  },
};
</script>
// Child.vue

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

<script>
export default {
  name: "ChildVue",
  inject: ['msg'],            // 기존의 props를 제거하고 inject로 data를 받아주면 되는데
};                            // 배열데이터로 받아주면 된다.
</script>

 

provide, inject를 사용하면 위처럼 불필요한 단계를 거치는 것을 줄여줄 수 있다.

 

 

 

 

단 provide를 사용하면 반응성을 제공할 수가 없기 때문에

 

처음에 한번 값을 보여줄 때 사용한다거나

아래와 같이 computed를 사용해서 값이 변화하는 것을 확인할 수 있도록 하여야 한다.

 

// App.vue

<template>
  <div id="app">
    <parent />   
  </div>
</template>

<script>
import Parent from "@/components/Parent.vue";
import { computed } from 'vue';

export default {
  name: "App",
  components: { Parent },

  data() {
    return {
      message: "hello world",
    };
  },
  provide() {                   
    return {                        // computed를 넣어줘서 계산된 데이터로
      msg: computed(()=>{           // 넘겨준다
        return	this.message
      })
    };
  },
};
</script>
// Child.vue

<template>
  <div>
    {{ msg.value }}          // object의 value값을 불러준다
  </div>
</template>

<script>
export default {
  name: "ChildVue",
  inject: ['msg'],            // object로 넘어오게 된다 
};                           
</script>

'Vue.js' 카테고리의 다른 글

[Vue.js] 템플릿 문법  (0) 2023.01.05
[Vue.js] v-if / v-show  (0) 2022.12.28
[Vue.js] script안에 들어가는 옵션 정리 /라이프 사이클 훅  (0) 2022.12.26
vue.js - CDN, npm , CLI 설치  (0) 2022.04.19