插槽基本使用

父组件

index.vue

<son1>
  <template>
    I'm content
  </template>
</son1>

components: {
    son1: () => import('./son1.vue'),
}

子组件

son1.vue

<div>
  <!-- 定义插槽 -->
  <!-- 定义可以用来被替换的结构 -->
  <slot>内容</slot>
</div>
<div>底部</div>

具名插槽

  • 插槽有一个name属性

父组件

index.vue

<son2>
  <!-- 简写形式 vant -->
  <template #content>I'm content</template>
  <template #foot>I'm foot</template>

  <!-- 原始形式 -->
  <template v-slot:content>I'm content</template>
  <template v-slot:foot>I'm foot</template>

  <!-- 被废弃的用法:element -->
  <template slot="content">我是内容</template>
  <template slot="foot">我是底部</template>
</son2>

components: {
    son2: () => import('./son2.vue'),
}

子组件

son2.vue

<div>
  <!-- 定义插槽 -->
  <!-- 定义可以用来被替换的结构 -->
  <slot name="content">内容</slot>
</div>
<div>
  <slot name="foot">底部</slot>
</div>

匿名插槽

  • 又叫默认插槽,单个插槽
  • 它不需要设置name属性,它隐藏的name属性为default

父组件

index.vue

<son3>
  <template slot="content">我是内容</template>
  <template slot="foot">我是底部</template>
  <template #default>
    我是头部的默认插槽
  </template>
</son3>

components: {
    son3: () => import('./son3.vue'),
}

子组件

son3.vue

<div>
  <!-- 没有 name 属性的插槽叫做默认插槽 -->
  <slot>头部</slot>
</div>
<div>
  <slot name="content">内容</slot>
</div>
<div>
  <slot name="foot">底部</slot>
</div>

作用域插槽

作用域插槽其实就是可以传递数据的插槽。子组件中的一些数据想在父组件中使用,必须通过规定的方法来传递。在官方文档中提出了一条规则,父级模板里的所有内容都是在父级作用域中编译的。子模板里的所有内容都是在子作用域中编译的。如果你在父组件直接使用子组件中的值,是会报错的。

父组件

index.vue

    <son4>
      <!-- 给每本书添加一个 《》 -->
      <!-- 简写形式: vant -->
      <template #content="{list,a}">
        <ol>
          <li v-for="(item, index) in list" :key="index">
            《{{ item.name }}》
          </li>
        </ol>
      </template> 

      <!-- 原始形式 -->
      <template v-slot:content="{list}">
        <ol>
          <li v-for="(item, index) in list" :key="index">
            《{{ item.name }}》
          </li>
        </ol>
      </template>

      <!-- element中被废弃的写法 -->
      <template slot="content" slot-scope="{ list, a }">
        <ol>
          <li v-for="(item, index) in list" :key="index">
            《{{ item.name }}》
          </li>
        </ol>
        <div>a:{{ a }}</div>
      </template>
    </son4>

子组件

son4.vue

<div>
  <slot name="content" :list="list" a="a">
    <ol>
      <li v-for="(item, index) in list" :key="index">
        {{ item.name }}
      </li>
    </ol>
  </slot>
</div>

data () {
  return {
    list: [
      { id: 1, name: '三国演义' },
      { id: 2, name: '红楼梦' },
      { id: 3, name: '西游记' },
      { id: 4, name: '水浒传' }
    ]
  }
}

菜鸟前端
10 声望0 粉丝