一个非prop的attribute是指传向一个组件,但是该组件并没有相应props或emits定义的attribute。常见的示例包括class、style和id属性。
1.Attribute继承
当组件返回单个根节点时,非prop attribute将自动添加到根节点的attribute中。
- 例如在组件实例中,如果我们需要通过date-status attribute定义组件的状态,它将应用于根节点
- 同样的规则也适用于事件监听器
- 当有一个具有change事件的HTML元素将作为组件的根元素时,可能会有帮助
- 在这种情况下,change事件监听器从父组件传递到子组件,它将在原生select的change事件上触发,不需要显示地从组件发出事件
2.禁用Attribute继承
如果不希望组件的根元素继承attribute,可以在组件的选项中设置inheritAttrs:false。
- 禁用attribute继承的常见情况是需要将attribute应用于根节点之外的其他元素
- 通过将inheritAttrs选项设置为false,可以访问组件的$attrs property,该property包括组件props和emits property中未包含的所有属性(例如class、style、v-on监听器等)
- 如果需要将所有非prop attribute应用于input元素而不是根div元素,则可以使用v-bind缩写来完成
app.component('date-picker', {
inheritAttrs: false,
template:`
<div>
<input v-bind="$attrs" />
</div>`
})
- 有了这个新配置,data-status attribute将应用于input元素:
<!-- Date-picker 组件 使用非 prop attribute -->
<date-picker data-status="activated"></date-picker>
<!-- 渲染 date-picker 组件 -->
<div class="date-picker">
<input type="datetime-local" data-status="activated" />
</div>
3.多个根节点上的Attribute继承
与单个根节点组件不同,具有多个根节点的组件不具有自动attribute fallthrough(隐式贯穿)行为,如果未显示绑定$attrs,将发出运行时警告。
// 这将发出警告
app.component('custom-layout', {
template: `
<header>...</header>
<main>...</main>
<footer>...</footer>
`
})
// 没有警告,$attrs被传递到<main>元素
app.component('custom-layout', {
template: `
<header>...</header>
<main v-bind="$attrs">...</main>
<footer>...</footer>
`
})