nonProps
컴포넌트에 전달되지만, props나 emit에 정의된 특성을 지니고 있지 않은 속성 또는 이벤트 리스너
nonProps
기본
ex)class, style, v-on
부모Component
<MyButton class="hello"></MyButton>
MyButton.vue
<template>
  <button>
    test button
  </button>
</template>
 
자동으로 nonProps 속성을 상속받고 싶지 않으면 => inheritAttrs: false선언
만약 root element가 두개이상이면?
MyButton.vue
<template>
  <div>
    root div
  </div>
  <button>
    test button
  </button>
</template>
위와 같이 두개이상의 root element가 있다면 부모 Component가 어떤 element에게 전달해야할지 모르므로 console에 경고메세지가 나타난다
 
{{ $attrs }}를 사용하자
<template>
  <div>
    root div
  </div>
  <button v-bind="$attrs">
    test button
  </button>
</template>
 
<button :class="$attrs.class">
  test button
</button>
요런식으로 attrs에서 개별적으로 가져오는 것도 가능. click이벤트는 attrs.onClick이다
emit함수는 왜 emit에 등록해야하나
자식 Component에서 emit함수를 통해 “click”이라는 이벤트를 전달하려한다
<template>
  <div>
    root div
  </div>
  <button v-bind="$attrs" @click="$emit('click')">
    test button
  </button>
</template>
부모 Component에서 자식Componet로부터 “click”이라는 이벤트를 전달받으면 sayHello이벤트를 실행한다
<script setup>
  import { ref } from 'vue'
  import MyButton from './MyButton.vue'
  const sayHello= () => alert("hello");
</script>
<template>
  <MyButton class="hello" @click="sayHello"></MyButton>
</template>
이제 버튼을 클릭하면 alert()가 한번 실행되어야하는데 두번이 실행된다
그 이유는? 부모Component에서 선언한 v-on 즉,@click이 자식Component에게 상속되기때문이다!
그렇기때문에 emit에 따로 등록해줘야한다
const emit = defineEmits({
  'click': null, 
  
})
cf) 만약 자식Componet가
<button v-bind="$attrs" @click="$emit('sayHelloSign')">라면 부모는<MyButton class="hello" @sayHeeloSign="sayHello"></MyButton>으로 되겠지?
참고자료: Vue3 완벽 마스터: 기초부터 실전까지 - “기본편”
 
       
      
댓글 쓰기