본문 바로가기
프론트엔드/Vue.js

컴포지션 API - props, context

by step 1 2021. 8. 5.
반응형

컴포지션 API에서 props, context 데이터를 가져오는 방법

 

기존코드

  mounted () {
    console.log(this.color)
    console.log(this.$attrs)
  },
  methods: {
    hello() {
      this.$emit('hello')
    }
  },

컴포지션 API를 이용한 코드(setup 메소드 내부에 선언)

setup(props, context) {
    function hello() {
      context.emit('hello')
    }
    onMounted(() => {
      console.log(props.color)
      console.log(context.attrs)
    })

    return {
      hello
    }
  }

 

예제 코드 App.vue

<template>
  <MyBtn
    class="happy"
    style="color: red;"
    color="#ff0000"
    @hello="log">
    Apple
  </MyBtn>
</template>

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

 

MyBtn 코드 (component)

<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'],
  // mounted () {
  //   console.log(this.color)
  //   console.log(this.$attrs)
  // },
  // methods: {
  //   hello() {
  //     this.$emit('hello')
  //   }
  // },

  setup(props, context) {
    function hello() {
      context.emit('hello')
    }
    onMounted(() => {
      console.log(props.color)
      console.log(context.attrs)
    })

    return {
      hello
    }
  }
}
</script>

 

브라우저 확인

반응형

'프론트엔드 > Vue.js' 카테고리의 다른 글

Vue Router (페이지 이동)  (0) 2021.08.09
N대1 연관관계  (0) 2021.08.08
컴포지션 API - 기본옵션과 라이프사이클  (0) 2021.08.05
컴포지션 API - 반응형 데이터  (0) 2021.08.05
컴포넌트 - Refs  (0) 2021.08.04