남과 같이 해선 남 이상이 될 수 없다.

Vue

[Vue.js] 컴포지션 API - props, context

맨동 2021. 7. 1. 13:56
728x90

컴포지션 API - props, context

1. 전달인자

setup 펑션은 2가지 전달인자를 가집니다

  1. props
  2. context

1.1 Props

setup 펑션의 첫번째 전달인자는 props입니다. 표준 컴포넌트에서 예상하는 것처럼 setup 내부의 props는 반응성이 있고, 새로운 props가 전달되면 업데이트됩니다.

1.2 Context

setup펑션의 두번째 전달인자는 context입니다. context는 3가지 컴포넌트 프로퍼티를 가지는 일반 JavaScript 객체입니다.

2. 컴포넌트 속성에 접근하기

setup이 실행될 때, 컴포넌트 인스턴스는 아직 생성되지 않았습니다. 결과적으로 아래와 같은 속성에만 접근할 수 있습니다.

  • props
  • attrs
  • slots
  • emit

즉, 다음 컴포넌트 옵션에는 접근할 수 없습니다:

  • data
  • computed
  • methods

3. 컴포지션 API 비교 예시

3.1 컴포지션 API 사용 전 코드 예시

//App.vue
<template>
  <MyBtn
    class="orosy"
    style="color: red;"
    color="#ff0000"
    @hello="log">
    Apple
  </mybtn>
</template>
<script>
import MyBtn from '~/components/MyBtn'

export default {
  components: {
    MyBtn
  },
  methods: {
    log() {
      console.log('Hello world!')
    }
  }
}
</script>

//MyBtn.vue
<template>
  <div
    v-bind="$attrs"
    class="btn"
    @click="hello">
    <slot></slot>
  </div>
</template>
<script>
export default {
  inheritAttrs: false,
  props: {
    color: {
      type: String,
      default: 'gray'
    }
  },
  emits: ['hello'],
  mounted() {
    console.log(this.color)
    console.log(this.$attrs)
  },
  methods: {
    hello() {
      this.$emit('hello')
    }
  }
}
</script>

3.2 컴포지션 API 사용 후 코드 예시

//MyBtn.vue
<template>
  <div
    v-bind="$attrs"
    class="btn"
    @click="hello">
    <slot></slot>
  </div>
</template>
<script>
import { onMounted } from 'vue'
export default {
  inheritAttrs: false,
  props: {
    color: {
      type: String,
      default: 'gray'
    }
  },
  emits: ['hello'],
  setup(props, context) {
    function hello() {
      context.emit('hello')
    }
    onMounted(() => {
      console.log(props.color)
      console.log(context.attrs)
    })

    return {
      hello
    }
  }
}
</script>

4. this 사용법

setup() 내부의 this는 현재 활성화된 인스턴스에 대한 참조가 아닙니다. 다른 컴포넌트 옵션들이 resolved가 되기 전에 setup()이 호출되었기 때문에, setup() 내부의 this는 다른 옵션 내부의 this와 다르게 동작합니다. 이로인해 다른 Options API와 함께 setup()를 사용할 때 혼동이 발생할 수 있습니다.

728x90

'Vue' 카테고리의 다른 글

[Vue.js] 컴포지션 API  (0) 2021.07.01
[Vue.js] 컴포넌트 - Refs  (0) 2021.06.30
[Vue.js] 컴포넌트 - Provide, Inject  (0) 2021.06.30
[Vue.js] 컴포넌트 - Slot  (0) 2021.06.30
[Vue.js] 컴포넌트 - Emit  (0) 2021.06.30