Props, Context

토리최고·2022년 1월 19일

Composition API

목록 보기
3/3
post-thumbnail

기존 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>

<style>

</style>

Composition API가 적용된 MyBtn.vue

여러가지 문법이 적용된 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>

<style>

</style>

Default App.vue

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

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

<style>

</style>

0개의 댓글