[Vue.js] props, context

OROSY·2021년 5월 5일
0

Vue.js

목록 보기
30/30
post-thumbnail

컴포지션 API - props, context

Vue.js의 컴포지션 API에서의 propscontext 사용에 대해 알아보도록 합시다. 더욱 자세한 사항은 공식 문서를 참고해주시기 바랍니다.

1. 컴포지션 API 비교 예시

컴포지션을 사용 시 props, context는 어떻게 활용해야하는지 직접 예시를 통해 확인하도록 하겠습니다.

1.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>

1.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>

위와 같이 복잡하지 않게 코드를 작성할 수 있으며, App.vue 파일에는 변화 없이 컴포넌트인 MyBtn.vue 파일만 수정을 진행해주시면 됩니다.

profile
Life is a matter of a direction not a speed.

0개의 댓글