片段
  • Vue3 一个模板不再限制有多个根节点
    • (多个根节点上的 Attribute 继承) 需要显式定义 attribute 应该分布在哪里。否则 控制台会给出警告提示
    <template>
        <header></header>
        <main v-bind="$attrs"></main>
        <!-- 父组件传的方法和参数可以通过 $attrs 访问 ,子组件 props 和 emits 中 出现的方法和参数不会出现在 $attrs 中-->
        <footer></footer>
    </template>
  • $attrs
    • 包含了父作用域中不作为组件 props 或自定义事件的 attribute 绑定和事件。当一个组件没有声明任何 prop 时,这里会包含所有父作用域的绑定,并且可以通过 v-bind="$attrs" 传入内部组件
    • $attrs 包含所有的 attribute,这使得把它们全部应用到另一个元素上更加容易(包括style和class)
  • 非 Prop 的 Attribute
    • 一个非 propattribute 是指传向一个组件,但是该组件并没有相应 propsemits 定义的 attribute
    • 大致就是父组件中定义了属性和方法,子组件内部没有定义props和emits或者是定义了没有完全接收父组件传过来的全部的属性和方法,这些属性和方法就会被添加到 attribute 中
  • Attribute 继承
    • 当组件返回单个根节点时,非 prop attribute 将自动添加到根节点的 attribute
  • 禁用 Attribute 继承
    • 如果你不希望组件的根元素继承 attribute,你可以在组件的选项中设置 inheritAttrs: false
    • 可以使用 v-bind 来规定 非 Prop 的 Attribute 应用到哪个元素上
app.component('date-picker', {
  inheritAttrs: false,
  template: `
    <div class="date-picker">
      <input type="datetime-local" v-bind="$attrs" />
    </div>
  `
})

<!-- 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>
Logo

前往低代码交流专区

更多推荐