-
컴포지션 API - props, contextVue/컴포지션 API 2021. 7. 22. 04:08
예제
App.vue
<template> <MyBtn class="ITBlue" 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
<!-- v-bind="$attrs" 부모 컴포넌트(APP.vue) 모든 속성이 상속이 됨 --> <!-- 클릭을 하면 hello() 메소드가 실행 --> <template> <div v-bind="$attrs" class="btn" @click="hello"> <slot></slot> </div> </template>
<script> export default { /* 속성을 상속 받지 않겠다. v-bind를 통해 상속 직접 지정 */ inheritAttrs: false, props: { color: { type: String, default: 'gray' } }, /* 부모 컴포넌트에 있는 hello 이벤트를 정의 */ emits: ['hello'], mounted() { console.log(this.color) console.log(this.$attrs) }, methods: { hello() { this.$emit('hello') } } } </script>
컴포지션 API 리팩토링
MyBtn.vue
<template> <div v-bind="$attrs" class="btn" @click="hello"> <slot></slot> </div> </template>
<script> import { onMounted } from 'vue' export default { /* 속성을 상속 받지 않겠다. v-bind를 통해 상속 직접 지정 */ inheritAttrs: false, props: { color: { type: String, default: 'gray' } }, /* 부모 컴포넌트에 있는 hello 이벤트를 정의 */ emits: ['hello'], setup(props, context) { function hello() { /* context는 $제거 해야함 */ context.emit('hello') } onMounted(() => { console.log(props.color) /* context는 $제거 해야함 */ console.log(context.attrs) }) return { hello } } } </script>
'Vue > 컴포지션 API' 카테고리의 다른 글
컴포지션 API - 기본 옵션과 라이프 사이클 (0) 2021.07.22 컴포지션 API - 반응형 데이터 (반응성) (0) 2021.07.20 컴포지션 API (0) 2021.07.20