最近写uniapp打包成h5和微信小程序端,在使用插槽时遇到了各种问题,记录一下
- 动态插槽在小程序不生效,
- 使用插槽,小程序端样式错乱,
- 使用v-if语法,插槽默认值不生效
1. 动态插槽在小程序不生效
定义插槽
js
// #ifdef H5
<slot :name="`content-${index}`"></slot>
// #endif
// #ifdef MP-WEIXIN
<slot name="content-{{index}}"></slot>
// #endif
使用插槽
js
// #ifdef H5
<template
v-for="(item, index) in formData"
v-slot:[`content-${index}`]
:key="item.id"
>
// #endif
// #ifdef MP-WEIXIN
<view
v-for="(item, index) in formData"
slot="content-{{index}}"
:key="item.id"
>
// #endif
按网上的方法,还是不显示,我把template改成view就显示可以了。
2. 使用插槽,小程序端样式错乱
小程序在使用插槽时会默认在最外层加view,在使用时发现默认插槽加上#default也会,可能就会导致样式错乱。
默认插槽通过以下写法可以避免包裹一层view,不过最外层还是会有一层组件名路径的标签,如果还是错乱,还是要通过另外写样式来兼容
如果是具名插槽,也只能另外写样式处理,目前没找到好的解决方案
js
// #ifdef H5
<template #default>
// #endif
// #ifdef MP-WEIXIN
<template>
// #endif
3.使用v-if语法,插槽默认值不生效
遍历展示时,有的数据需要使用插槽,有的不需要
一开始我是这样写的,结果所有的数据都有slot标签,只是有的是空的,默认值就展示不出来
js
<Cell v-for="item in formData">
<template v-if="item.type"></template>
</Cell>
只能通过以下方式写,但增加了代码量,如果遇上更复杂的插槽会更麻烦,也是没找到好的解决方案
js
<view v-for="item in formData">
<Cell v-if="item.type">
<template></template>
</Cell>
<Cell v-else>
<template ></template>
</Cell>
</view>
纯做记录,如果jy们有好的方案,欢迎评论