vue中的插槽:默认插槽和具名插槽.

152 阅读1分钟

vue中的插槽

  1. 组件通过插槽传入自定义结构
  2. 用于实现组件的内容分发, 通过 slot 标签, 可以接收到写在组件标签内的内容
  3. vue提供组件插槽能力, 允许开发者在封装组件时,把不确定的部分定义为插槽

格式

在定义组件时,在template中用slot来占个坑;

使用时,将组件之间的内容来填坑;

示例

组件进阶-具名插槽

目标

掌握具名插槽的使用

背景

当一个组件内有2处以上需要外部传入标签的地方

格式

定义:

使用:

  • <template #xxx>;

图示:

  1. 传入的标签可以分别派发给不同的slot位置
  2. v-slot一般跟template标签使用 (template是html5新出标签内容模板元素, 不会渲染到页面上, 一般被vue解析为内部标签)

示例

  1. 子组件-Pannel2.vue
<div class="container" v-show="isShow">
    <slot name="one"></slot>
    <slot name="two"></slot>
</div>

2 .父组件-UseSlot2.vue

v-slot可以简化成#使用

v-bind可以省略成:    

v-on: 可以省略成@  

v-slot: 可以简化成#

写法1:

<Pannel2>
    <template v-slot:one>
		<img src="../assets/mm.gif" alt="" />
    </template>
    <template v-slot:two>
		<span>我是文字哦</span>
    </template>
</Pannel2>

写法2:

<Pannel2>
    <!-- 简化写法 -->
    <template #one>
		<div>
            <p>寒雨连江夜入吴,</p>
            <p>平明送客楚山孤。</p>
            <p>洛阳亲友如相问,</p>
            <p>一片冰心在玉壶。</p>
        </div>
    </template>
    <template #two>
		<img src="../assets/mm.gif" alt="" />
    </template>
</Pannel2>

小结

  1. slot有可以设置多个
  2. 定义组件时:slot的name属性起插槽名
  3. 使用组件时, template配合#插槽名传入具体html标签或组件