Vue3 정복기(9일차)

최충열·2022년 5월 18일
post-thumbnail

컴포넌트 속성상속

클래스와 스타일을 상속하는데 MyBtn에서보면 라이프사이클 Create로 컴포넌트가 만들어진 직후에 this.attrs선언attrs는속성값을의미함으로vbind="attrs 선언 attrs는 속성값을 의미함으로 v-bind="attrs"가 가능하고
:class="attrs.class",:style="attrs.class", :style="attrs.style" 두개로 선언해도 상관없다.

App.vue
<template>
  <MyBtn
    class="heropy"
    style="color: red;">
    Banana
  </MyBtn>
</template>

<script>
import MyBtn from "~/components/MyBtn";

export default {
  components: {
    MyBtn,
  }
};
</script>
MyBtn.vue
<template>
  <div class="btn">
    <slot></slot>
  </div>
  <h1
    v-bind="$attrs"></h1>
</template>

<script>
export default {
  inheritAttrs: false,
  created() {
    console.log(this.$attrs)
  }
}
</script>

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

Emit

app.vue

v-model로 만든 msg의 양방향 데이터 통신

watch로 감시해서 실행한다.
changeMsg 이벤트가 발생되면 @change-msg가 실행된다.
그러면 logMsg메소드가 동작되며 메세지를 받아서 콘솔로 뿌리는데 msg가 MyBtn.vue에있는 $emit에 작성되어있는 this.msg가 되는것이며 결국 이게 양방향 데이터로 연결되어있어서 출력이된다.
복잡해보이지만 따지고 보면 별로 안어렵다네...
상당히 어렵지만 계속 공부해야겠다.

<template>
  <MyBtn
    @heropy="log"
    @change-msg="logMsg">
    Banana
  </MyBtn>
</template>

<script>
import MyBtn from "~/components/MyBtn";

export default {
  components: {
    MyBtn,
  },
  methods: {
    log(event) {
      console.log('Click!!')
      console.log(event)
    },
    logMsg(msg) {
      console.log(msg)
    }
  }
};
</script>
MyBtn.vue
<template>
  <div class="btn">
    <slot></slot>
  </div>
  <h1 @dblclick="$emit('heropy', $event)">
    ABC
  </h1>
  <input
    type="text"
    v-model="msg" />
</template>

<script>
export default {
  emits: [
    'heropy',
    'changeMsg'
  ],
  data () {
    return {
      msg: ''
    }
  },
  watch: {
    msg() {
      this.$emit('changeMsg', this.msg)
    }
  }
}
</script>

<style scoped>
  .btn {
    display: inline-block;
    margin: 4px;
    padding: 6px 12px;
    border-radius: 4px;
    background-color: gray;
    color: white;
    cursor: pointer;
  }
</style>
profile
프론트엔드가 되고싶은 나

0개의 댓글