Yejun Cheon
log
study
read
coffee
Sign In
배운 것을 정리합니다.

[Vue 05] Vue attr

예
예준천
카테고리
  1. Vue

attr가 뭐야

By default, everything in $attrs will be automatically inherited on the component's root element if there is only a single root element. This behavior is disabled if the component has multiple root nodes, and can be explicitly disabled with the inheritAttrs option.
attr는 props나 emit으로 미쳐 받지 못한 속성들을 모두 잡아준다. 명시적으로 모두 정의하기 어려운 속성들을 가져오거나, 다시 자신의 자식에게 드릴링 할때 유용하다.
<template>
  <child-component type="text" 
        placeholder="Enter your name" />
</template>
<template>
  <input v-bind="attrs" />
</template>

<script setup>
const attrs = useAttrs();
</script>
커스텀 inut을 만들었는데, input태그에 여러 속성들을 추가하고 싶은데 모두 props로 명시적으로 정의하기는 귀찮다. 그럴때 attrs로 남은 속성 다 받아와서 input에 v-bind로 동적으로 HTML속성을 추가해주면 된다.

falltrhough attributes

Fallthrough Attributes에 대해 조금더 알아보자.
•
부모에서 컴포넌트를 선언하며 추가한 속성들 중 props,emits로 잡지 않은 모든게 들어있다.
•
style, class도 들어온다.
•
inheritAttrs 를 따로 설정하지 않는다면, Fallthrough Attributes는 해당컴포넌트의 루트노드로 자동으로 바인딩 된다.
•
class와 style의 경우, 이미 존재한다면 자동으로 merge된다.
•
이벤트가 이미 있는 경우, 기존이벤트, Fallthrough Attributes로 자동 바인딩 된 이벤트 모두 실행된다.
•
중첩된 컴포넌트에서도 잘 전달된다.
•
만약 루트 엘리먼트가 여러개인 경우, 오류가 발생한다. 이 경우 $attrs 로 바인딩 할 엘리먼트를 정해주거나, inheritAttrs 를 false로 설정 후 useAttrs() 로 받아오고 사용하면 된다.
•
웬만해서는 반응형이 유지된다.
참고 : https://vuejs.org/guide/components/attrs.html

v-bind

v-bind에 객체를 넣으면, 각 객체의 속성과 값이 해당 HTML요소 또는 컴포넌트의 속성으로 들어가고, 객체의 변경사항은 반영된다. 여기서는 useAttrs나 $attrs로 가져온 속성들을 한번에 다시 바인딩하는데 사용된다.

사용예시

https://vue-ufykrc.stackblitz.io/
Subscribe to 'Yejun Cheon'
Subscribe to my site to be the first to receive notifications and emails about the latest updates, including new posts.
Join Slashpage and subscribe to 'Yejun Cheon'!
Subscribe
👍