这里使用场景式uni-app编译微信小程序,其他场景未测试
在开发中使用uni官方的 uni-list-item
组件,但是角色不够灵活,于是想着在其组件内添加slot插槽,可以自定义icon及note部分。这里以note部分为例:
<view class="uni-list-item__content">
<view class="uni-list-item__content-title">{{ title }}</view>
<view v-if="note" class="uni-list-item__content-note">{{ note }}</view>
<view v-else><slot name="note"></slot></view>
</view>
如上打码,第4行是添加的slot插槽,用来自定义列表项的描述信息部分,如果有note属性,则slot失效,没有note则slot生效。
这里有个坑:slot上不能直接使用 v-else
,微信小程序会报错
在使用组件的时候,是这样的:
<template slot="note">
<span class="uni-list-item__content-note">123</span>
</template>
效果如下图:
如果使用组件时,直接给span添加slot,class的样式并没有起作用,效果如图:
另外,如果使用组件时,使用v-slot指令,描述信息这个123 是不会显示的:
<template v-slot:note>
<span class="uni-list-item__content-note">123</span>
</template>
效果如下图:
综述:uni-app开发微信小程序时,使用slot插槽时:
- 不要在slot上添加v-if v-for等指令
- 使用组件是使用slot=”name”的方式,不要使用v-slot
- 使用组件时,插槽内容用template标签包裹起来