DEV Community

Cover image for Vue Prop | 禁用Attribute繼承
周柏諭 BO-YU CHOU
周柏諭 BO-YU CHOU

Posted on • Updated on

Vue Prop | 禁用Attribute繼承

前言

一般來說,當在父組件傳遞attribute給子組件時,

// parent
<basic-input disabled>

// child
<input>
Enter fullscreen mode Exit fullscreen mode

經渲染後會變成

<input disabled>
Enter fullscreen mode Exit fullscreen mode

但是我們的子組件結構有時不會只有一個節點,通常因為css需要,外層會再包一個標籤,例如:

<div class="container">
    <input>
</div>
Enter fullscreen mode Exit fullscreen mode

經渲染後會變成

<div class="container" disabled>
    <input>
</div>
Enter fullscreen mode Exit fullscreen mode

disabled屬性會直接繼承在子物件的根結點上。

這時如果不希望组件的根元素繼承 attribute,那該怎麼辦呢?

禁用Attribute繼承

這種情況就需要到組件的option中設置inheritAttrs: false,禁用attribute繼承。

Vue.component('my-component', {
  inheritAttrs: false,
  // ...
})
Enter fullscreen mode Exit fullscreen mode

如果子組件是單一檔案的話,在子組件內設置:

export default {
  name: 'my-component',
  inheritAttrs: false,
  props: {
    disabled: Boolean
  }
}
Enter fullscreen mode Exit fullscreen mode

設置完後,這時你就可以手動決定哪些attribute賦予哪個元素,把子物件改為:

<div class="container">
    <input disabled>
</div>
Enter fullscreen mode Exit fullscreen mode

這樣disabled屬性就不會跑到根結點上

inheritAttrs: false在寫基礎組件的時候很常用到,例如inputselect之類的功能型標籤,

有關他們屬性typedisabledplacehodler等都希望綁在子物件的特定標籤上。

也可以看看官方文件的範例:

Vue.component('base-input', {
  inheritAttrs: false,
  props: ['label', 'value'],
  template: `
    <label>
      {{ label }}
      <input
        v-bind="$attrs"
        v-bind:value="value"
        v-on:input="$emit('input', $event.target.value)"
      >
    </label>
  `
})

// parent component 使用 <base-input>
<base-input
  label="Username:"
  v-model="username"
  required
  placeholder="Enter your username"
></base-input>
Enter fullscreen mode Exit fullscreen mode

如果對於官方範例子物件v-bind:valuev-on:input有疑問
https://yubo0826.github.io/vue-blog/#/posts/6

$attrs有疑惑的

https://v2.cn.vuejs.org/v2/api/#vm-attrs

總結

  1. 當設置inheritAttrs: true(預設),子組件根節點會渲染出父節點傳遞過來的attrribute
  2. 當設置inheritAttrs: false,子組件根節點不會渲染出父節點傳遞過來的attrribute

參考

  1. 官方文件(Vue2、Vue3關於禁用屬性繼承基本一樣) https://v2.cn.vuejs.org/v2/guide/components-props.html
  2. https://blog.csdn.net/weixin_41977619/article/details/116597022

Top comments (0)