关于vue.js:vue插槽slot

2次阅读

共计 1546 个字符,预计需要花费 4 分钟才能阅读完成。

插槽

  1. 默认插槽
  2. 具名插槽
  3. 作用域插槽

1 默认插槽

  • 数据与构造在父组件
  • 插槽在子组件

子组件

<!-- 复用的构造 -->
...

<!-- 不复用的地位 -->
<slot> 无插入时默认构造 </slot>

<!-- 复用的构造 -->
...

父组件

<Component >
    <img/>
</Component>
    <video/>
<Component >
    <h3/>
<Component >

复用组件
每个被复用的组件有一部分构造或数据不同
从父组件中将不同的数据与构造填充到子组件的插槽中

2 具名插槽

  • 数据与构造在父组件中
  • 插槽在子组件中
  • 复用的组件有多个中央不同

子组件

<!-- 复用的构造 -->
...

<!-- 不复用的地位 1 -->
<slot name="slot1"> 默认值 1 <slot>

<!-- 复用的构造 -->
...

<!-- 不复用的地位 2 -->
<slot name="slot2"> 默认值 2 <slot>

父组件

<Component >
    <template v-slot:slot1>
        <img/>
    </template>
    <template v-slot:slot2>
        <video/>
    </template>
</Component>
    
<Component >
    <template v-slot:slot1>
        <h3></h3>
    </template>
    <template v-slot:slot2>
        <img/>
    </template>
</Component >

给每个插槽增加 name 属性
父组件插入的模板增加 v-slot 属性
无指定的模板 默认插入无 name 属性的插槽

3 作用域插槽

  • 构造在父组件
  • 数据与插槽在子组件
  1. 默认
    子组件

    <!-- 复用的构造 -->
    ...
    
    <!-- 不复用的地位 -->
    <slot :data1="food" :data2="drink"> 无插入时默认构造 </slot>
    
    <!-- 复用的构造 -->
    ...

    父组件

    <Component >
     <!-- 对象取值 -->
     <template v-slot="data">
         <h2>{{data.data1}}</h2>
     </template>
    </Component>
     
    <Component >
     <!-- 解构取值 -->
     <template v-slot="{data2}">
         <h3>{{data2}}</h3>
     </template>
    </Component >
  2. 具名
    子组件

    <!-- 复用的构造 -->
    ...
    
    <!-- 不复用的地位 -->
    <slot :data1="food" :data2="drink" name="slot1"> 无插入时默认构造 </slot>
    
    <!-- 复用的构造 -->
    ...
    
    <!-- 不复用的地位 -->
    <slot :data1="live" :data2="transport" name="slot2"> 无插入时默认构造 </slot>

    父组件

    <Component >
     <template v-slot:slot1="{{food}}">
         ...
     </template>
     <template v-slot:slot2="{{live}}">
         ...
     </template>
    </Component>
     
    <Component >
     <template v-slot:slot1="{{drink}}">
         ...
     </template>
    </Component >

v-slot:name是对具名插槽的抉择
v-slot="obj" 是对默认插槽的抉择 简写模式
下面两种办法尽量不要同时用,可能会呈现抉择不明确的谬误
v-slot:name="obj" 从具名插槽中接管值,在父组件中接管并编译实现再插入子组件
只有呈现多个插槽,尽量应用 template 中的 v -slot

举荐 应用 template 的 v -slot残缺的写法
v-slot:default=”obj”v-slot:other=”obj”
不举荐 应用slot="name"slot-scope="obj"

正文完
 0