컴포넌트-Provide, Inject

토리최고·2022년 1월 18일
0

Vue 문법

목록 보기
19/20
post-thumbnail

기존 prop

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의 정보를 모두 입력해서 넘겨줘야한다.

provide & inject

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>

computed

provide라는 개념을 통해 반응성을 유지해주는 데이터를 만들려면 computed라는 함수를 실행해서 그 내부에 call back함수를 만들어서 그 내에서 특정한 반응성을 가지고싶은 데이터를 반환해주면 된다.

App.vue

객체 구조분해로 vue라는 패키지를 가져옴
provide() msgcomputed라는 함수를 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라는 계산된 데이터를 가져와서 동작시키는 방법으로 해당하는 데이터의 반응성을 유지한 상태로 조상요소에서 후손요소로 데이터를 연결시켜줄 수 있는 구조를 만들어준다.

0개의 댓글

관련 채용 정보