• slot 插槽

简介:插槽是 Vue 中的一个特殊特性,它的作用是:在指定位置开辟一个空间,给未来的元素使用给,这里所谓的未来的元素就是组件的内容,但是 slot 已被废弃了。

<SlotDemo :url="website.url">{{website.title}}</SlotDemo>

<a :href="url">
    <slot>默认内容</slot>
</a>
export default{
    props: ['url']
}
  • 作用域插槽(slot-scope)

作用域插槽其实就是一个带有数据的插槽,我们知道组件中的数据只能在对应的组件模板中使用,在其他地方无法获取,那么要想在其他地方获取到该数据,就可以通过使用 slot-scope 来获取,但是 slot-scope 已被废弃。

slot-scope 用来绑定的是子组件的数据,在组件模板中书写所需 slot 插槽,并将当前组件的数据通过 v-bind 绑定在 slot 标签上。

// 子组件
<span>
  <slot v-bind:user="user">
    {{ user.lastName }}
  </slot>
</span>

绑定在 <slot> 元素上的 attribute 被称为插槽 prop。现在在父级作用域中,我们可以使用带值的 v-slot 来定义我们提供的插槽 prop 的名字:
// 父组件
<current-user>
  <template v-slot:default="slotProps">
    {{ slotProps.user.firstName }}
  </template>
</current-user>

(1)独占默认插槽的缩写语法

只要出现多个插槽,请始终为所有的插槽使用完整的基于 <template> 的语法:

<current-user>
  <template v-slot:default="slotProps">
    {{ slotProps.user.firstName }}
  </template>

  <template v-slot:other="otherSlotProps">
    ...
  </template>
</current-user>

(2)解构插槽 Prop

作用域插槽的内部工作原理是将你的插槽内容包裹在一个拥有单个参数的函数里,意味着 v-slot 的值实际上可以是任何能够作为函数定义中的参数的 JavaScript 表达式。可以使用 ES 来传入具体的插槽 prop,例如:

<current-user v-slot="{ user }">
  {{ user.firstName }}
</current-user>
  • v-slot 内置指令

从 vue2.6 开始,Vue 为具名插槽和作用域插槽引入了一个全新的语法,即 v-slot 指令。目的就是想要同一 slot 和 scope-slot 语法,使代码更加规范和清晰。

作用域插槽

<ScopedSlotDemo url="website.url">
    <template v-slot="slotProps">
        {{slotProps.slotData.title}}
    </template>
</ScopedSlotDemo>

<a :href="url">
    <slot :slotData="website">{{website.subTitle}}</slot>
</a>

具名插槽

<NamedSlot>
    <!-- 缩写 <template #header> -->
    <template v-slot:header>
        <h1>将插入 header slot 中</h1>
    </template>
    <p>将插入到 main slot 中,即 未命名的 slot</p>
    <template v-slot:footer>
        <p>将插入到 footer slot 中</p>
    </template>
</NamedSlot>

<div class="container">
    <header>
        <slot name="header"></slot>
    </header>
    <main>
        <slot></slot>
    </main>
    <footer>
        <slot name="footer"></slot>
    </footer>
</div>

 

Logo

前往低代码交流专区

更多推荐