TechScribe Notes
19_Non-Prop 속성(fallthrough속성) 본문
1. Non-Prop 속성
: Props나 이벤트에 명시적으로 선언되지 않은 속성이나 이벤트. class,style,id~
2. 속성 상속
: 컴포넌트가 단일 루트 요소로 구성되어 있으면 non-prop 속성은 루트요소의 속성에 자동으로 추가되고 만약에 자식 컴포넌트요소에 이미 있는 class와 style속성이 정의 되어 있으면 부모로 받은 것과 병합된다.
<!-- template of <MyButton> -->
<button>click me</button>
<!-- 부모 컴포넌트 -->
<MyButton class="large" />
<!-- 최종 랜더링된 DOM -->
<button class="large">click me</button>
<!--자식 컴포넌트에 이미 클래스나 style 속성 있을 때 -->
<button class="btn">click me</button>
<!-- 최종 랜더링된 DOM -->
<button class="btn large">click me</button>
3. v-on 이벤트 리스너 상속
: 동일하게 상속 됨
<MyButton @click="onClick" />
<!-- @click 리스너는 MyButton의 루트요소인 <button>에 추가되고, 이미 <button>요소에
바인딩 된 요소가 있따면 두 리스너 모두 트리거 된다. -->
4. 속성 상속 비활성화
: inheritAttrs:false 옵션
- 자식 컴포넌트 루트요소 이외의 다른 요소에 Non-prop 속성을 적용하고 싶을 때
<template>
<button class="btn" data-link="hello">click me</button>
</template>
<script>
export default {
inheritAttrs: false,
};
</script>
- 적용하고 싶은 요소에 에서 Non-prop 속성에 접근할 수 있는 내장 객체 $attrs로 직접 접근 가능함
<template>
<p>Non-Prop 속성: {{ $attrs }}</p>
</template>
- $attrs 객체에는 컴포넌트에 선언되지 않은 속성을 포함하고 있음.
- props와 달리 Non-prop 속성은 JS에서 원래 대소문자를 유지하므로 foo-bar와 같은 경우 $attrs['foo-bar']로 접근해야함.
- @click과 같은 v-on리스너는 $attrs.onClick과 같이 함수로 접근할 수 있음
5. Non-Prop 속성을 특정요소에 모두 적용하는 법
: inheritAttrs: false와 $attrs를 이용
<template>
<label>
이름:
<input type="text" v-bind="$attrs" />
</label>
</template>
<script>
export default {
inheritAttrs: false,
};
</script>
<!-- 부모 컴포넌트 -->
<MyInput
class="my-input"
placeholder="didj"
@keyup="onKeyup"
data-message="Hello World!"
/>
*vue3 부터는 $listeners는 제거 되고 모든 리스너가 $attrs의 일부가 됨.
6. Fragments
: 다중 루트 노트 컴포넌트. vue2까지는 다중 루트 컴포넌트 오류 해결하려면 <div>태그 안에 넣어야했지만 vue3부터는 가능
<!-- Layout.vue -->
<template>
<header>...</header>
<main v-bind="$attrs">...</main>
<footer>...</footer>
</template>
7. 여러 루트노드의 속성 상속
: 자동으로 non-prop 속성이 상속 되지 않고 명시적으로 $attrs를 바인딩 하지 않으면 런타입 경고 발생.
<!--- 자식 컴포넌트 --->
<!-- CustomLayout.vue -->
<template>
<header></header>
<main></main>
<footer></footer>
</template>
<!-- 부모 컴포넌트 -->
<CustomLayout id="custom-layout"></CustomLayout>
<!--- 명시적으로 바인딩하면 경고 뜨지 않음 --->
<!-- CustomLayout.vue -->
<template>
<header></header>
<main v-bind="$attrs"></main>
<footer></footer>
</template>
8.JS에서 non-prop 속성 접근
setup()함수의 context.attrs 속성으로 노출 됨.
export default {
setup(props, context) {
console.log(context.attrs)
}
}
'project > Vue.js' 카테고리의 다른 글
21_Provide / Inject (0) | 2024.12.27 |
---|---|
20_slot (0) | 2024.12.26 |
18_Event(Emit) (1) | 2024.12.24 |
17_Props (0) | 2024.12.23 |
16_Single-File Component (SFC) (0) | 2024.12.12 |