非 Prop 的 Attribute

    一个非 prop 的 attribute 是指传向一个组件,但是该组件并没有相应 或 emits 定义的 attribute。常见的示例包括 、styleid 属性。

    当组件返回单个根节点时,非 prop attribute 将自动添加到根节点的 attribute 中。例如,在 <date-picker> 组件的实例中:

    如果我们需要通过 data status property 定义 <date-picker> 组件的状态,它将应用于根节点 (即 div.date-picker)。

    1. <!-- 具有非prop attribute的Date-picker组件-->
    2. <date-picker data-status="activated"></date-picker>
    3. <!-- 渲染 date-picker 组件 -->
    4. <div class="date-picker" data-status="activated">
    5. <input type="datetime" />
    6. </div>
    1. <date-picker @change="submitChange"></date-picker>

    当有一个 HTML 元素将 change 事件作为 date-picker 的根元素时,这可能会有帮助。

    1. app.component('date-picker', {
    2. template: `
    3. <select>
    4. <option value="1">Yesterday</option>
    5. <option value="2">Today</option>
    6. <option value="3">Tomorrow</option>
    7. `
    8. })

    在这种情况下, 事件监听器从父组件传递到子组件,它将在原生 selectchange 事件上触发。我们不需要显式地从 date-picker 发出事件:

    1. <div id="date-picker" class="demo">
    2. <date-picker @change="showChange"></date-picker>
    3. </div>

    如果你希望组件的根元素继承 attribute,你可以在组件的选项中设置 inheritAttrs: false。例如:

    通过将 inheritAttrs 选项设置为 false,你可以访问组件的 $attrs property,该 property 包括组件 propsemits property 中未包含的所有属性 (例如,classstylev-on 监听器等)。

    使用中的 date-picker 组件示例,如果需要将所有非 prop attribute 应用于 input 元素而不是根 div 元素,则可以使用 v-bind 缩写来完成。

    1. app.component('date-picker', {
    2. inheritAttrs: false,
    3. template: `
    4. <div class="date-picker">
    5. <input type="datetime" v-bind="$attrs" />
    6. </div>
    7. `

    有了这个新配置,data status attribute 将应用于 input 元素!

    1. <!-- Date-picker 组件 使用非 prop attribute -->
    2. <date-picker data-status="activated"></date-picker>
    3. <!-- 渲染 date-picker 组件 -->
    4. <input type="datetime" data-status="activated" />
    5. </div>
    1. // 这将发出警告
    2. app.component('custom-layout', {
    3. template: `
    4. <header>...</header>
    5. <main>...</main>
    6. <footer>...</footer>
    7. `
    8. })
    9. // 没有警告,$attrs被传递到<main>元素
    10. app.component('custom-layout', {
    11. template: `
    12. <header>...</header>
    13. <main v-bind="$attrs">...</main>
    14. <footer>...</footer>
    15. })