一、什么是插槽?
插槽就是子组件提供给父组件使用的一个占位符,用<slot></solt>表示父组件可以在这个占位符中填充任何模板代码。
二、插槽的用法
1.创建一个子组件,在uni.app中创建一个components目录新建一个textConten.vue子组件,在子组件中放一个solt占位符。
2.在父组件中给这个子组件填充内容
效果图
假设在子组件中不加solt,在父组件中不会扩展子组件内容
子组件
<template name="textConten">
<view>
<view >
这是一个测试内容
</view>
<!-- 这里可以插入内容 -->
<!-- <slot></slot> -->
</view>
</template>
父组件
<textConten>
<view >
我叫new world
</view>
</textConten>
界面显示
3.有时候我们需要多个插槽,所以有了具名插槽的概念,通俗的说就是给插槽起名字。
在子组件中定义两个插槽
<template name="textConten">
<view>
<view >
这是一个测试内容
</view>
<!-- 这里可以插入内容 -->
<view class="centerSlot" >
<slot name="name1"></slot>
</view>
<view class="bottomSlot">
<slot name="name2"></slot>
</view>
</view>
</template>
在父组件中引用插槽
<template>
<view class="content">
<image class="logo" src="/static/logo.png"></image>
<view class="text-area">
<text class="title">{{title}}</text>
</view>
<textConten>
<slot>这是没有不填加名字的</slot>
<text slot="name1">这是个内容11111</text>
<text slot="name2">这是第二个插槽</text>
</textConten>
<!-- <view :class="item.color?'bbb':''" v-for="(item,index) in list" @click="getItem(item)">
{{item.name}}
</view> -->
</view>
</template>
效果图:
4.作用域插槽
根据vue.js官网文档说是为了获取子组件才有的数据。虽然实际运用中还没碰到类似的情况,但是还模拟了一下。
在子组件data中定义一个数组list,然后给插槽通过v-model绑定一下。然后在父组件中把子组件绑定的名字作为attribute 绑定上去。
子组件代码
在父组件中
结果图
三、总结
1.在具名插槽中,如果父组件填充的内容没有指定子组件插槽的名称,那么,父组件扩展的内容将不会显示到界面上。
2.在具名插槽中,如果子组件没有默认插槽,而在父组件中指定插槽的名称,那么该内容也不会显示