ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 컴포지션 API - props, context
    Vue/컴포지션 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>

    댓글

Designed by Tistory.