若不想要讓屬性自動繼承,可以使用 inheritAttrs: false
來停用
用法:
<span>Fallthrough attribute: {{ $attrs }}</span>
eg.
子元件:
<script setup>
defineOptions({ inheritAttrs: false })
</script>
<template>
<div class="btn-wrapper">
<button class="btn" v-bind="$attrs">
Click Me
</button>
</div>
</template>
父元件:
<template>
<MyButton class="large" id="buy" @click="onBuy" />
</template>
透過 inheritAttrs: false
+ v-bind="$attrs"
屬性便不會落在外層 wrapper
而是掛到內部的按鈕上
如果有多個根節點 Vue 會不知道要將屬性透傳到哪裡
<header>...</header>
<main>...</main>
<footer>...</footer>
此時使用
子元件:
<script setup>
defineOptions({ inheritAttrs: false })
</script>
<template>
<header>Header</header>
<main v-bind="$attrs">Main</main>
<footer>Footer</footer>
</template>
父元件:
<template>
<CustomLayout id="custom-layout" @click="changeValue" />
</template>
將所有的父層屬性決定到 main
上面
ref:
https://zh-hk.vuejs.org/guide/components/attrs.html