iT邦幫忙

2025 iThome 鐵人賽

DAY 22
0
Vue.js

Vue.js 新手入門之路系列 第 22

Vue.js 新手入門之路 - fallthrough(二)

  • 分享至 

  • xImage
  •  

關閉自動傳透

若不想要讓屬性自動繼承,可以使用 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 而是掛到內部的按鈕上
https://ithelp.ithome.com.tw/upload/images/20250911/20178296FUirMEQ71D.png

多根節點的屬性繼承

如果有多個根節點 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 上面
https://ithelp.ithome.com.tw/upload/images/20250911/20178296KnTBeXkQSG.png

ref:
https://zh-hk.vuejs.org/guide/components/attrs.html


上一篇
Vue.js 新手入門之路 - fallthrough
下一篇
Vue.js 新手入門之路 - slot
系列文
Vue.js 新手入門之路25
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言