본문 바로가기
Frontend/Vue 2

[vue3] props, context

by SOLYI 2021. 10. 19.

setup 내부에서 props 와  context 사용하기

// App.vue
<template>
  <MyBtn
    class="heropy"
    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>
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>

<style scoped>
  .btn{
    display: inline-block;
    margin: 4px;
    padding:6px 12px;
    border-radius: 4px;
    background-color:grey;
    color: white;
    cursor: pointer;  
  }
</style>

반응형

'Frontend > Vue 2' 카테고리의 다른 글

[Netlify] 서버리스 배포  (0) 2021.10.22
[vue3] 동기? 비동기? promise  (0) 2021.10.21
[vue3] component api 적용/미적용 예제  (0) 2021.10.19
[vue3] composition api  (0) 2021.10.19
vue3 ref  (0) 2021.10.19