uniapp小程序 slot中无法传递外部参数的解决方案

最近在封装一个List组件,外部传给我数据,我循环后将每个Item部分slot到外部,由调用者自己去写item布局,类似ElementUI、iView的Tabe列表。
List:

<view v-if="list.length > 0" class="list-scroll__item" v-for="(item, index) in list" :key="item.id" @click="onClickItem(item)">
      <slot :item="item" :index="index"/>
</view>

调用:

 <list :list="list">
    <item slot-scope="{item}"  :item="item"></item>
  </list>


item是自定义每一项的样式组件,可自行脑补。
**不出意外这样就可以正常显示列表数据了**,如果出了意外只能显示一项请配置slot编译模式
scopedSlotsCompiler:legacy 为旧版编译模式,新版模式: auto 与 augmented,可切换尝试

不出意外就能正常显示了!

====================================================================

我现在还有第二个需求,就是item里有点击事件,我要将我点击的项目传递给每个slot的item,然后每个item根据数据做出变化。

现在改动一下:

<list :list="list">
    <item slot-scope="{item}"  :item="item"  :current="currentItem" @clickItem="(e)=>currentItem=e"></item>
  </list>

currentItem:是页面数据 @clickItem是接收item内部点击事件的数据,然后赋值给currentItem,

不知道您看明白了没?总的来说就是我在某一个item发生点击事件的时候,将传出来的值赋值给页面变量currentItem,然后把currentItem赋值给每个item,只有点击的item跟currentItem是一个时才做出某些变动,如果不一样则还原之前的变动。

就是这么个再平常不过的事件,但是currentItem死活都传不过去,具体讨论解释可参考:

https://github.com/dcloudio/uni-app/issues/495

反正就是无解!!!!!实在没有办法我就想其他笨办法先解决问题吧。

1、首先将:current="currentItem"移动到list组件上,然后list内增加props为current的接收对象,就变为:

<list :list="list" :current="currentItem" >
    <item slot-scope="{item}"  :item="item"  @clickItem="(e)=>currentItem=e"></item>
  </list>

List内部:

props:{

list: { type: Array, default: () => [] },
current:{ type:Object, default:()=>{} }
}

2、这样list组件就能接收到页面参数了,然后将list内部slot部分改动如下,将接收的参数抛出去:

<view v-if="list.length > 0" class="list-scroll__item" v-for="(item, index) in list" :key="item.id" @click="onClickItem(item)">
      <slot :item="item" :index="index" :current="current"/>
</view>

3、 到此外面的slot  item部分就能接收到该参数了

<list :list="list" :current="currentItem">
    <item slot-scope="{item,current}"  :item="item"  :current="current" @clickItem="(e)=>currentItem=e"></item>
  </list>

到此一个连贯的传值操作就结束了!总结如下:

slot部分不能直接传递页面参数,也就是作用域以外的参数,但是变相可以传递,

1、先传递给父组件,并且父组件内props接收该参数

2、父组件内slot将接收的参数slot出去,抛给slot复写的人

3、复写slot的人在接收该参数传递给自己复写的item部分,自己的item增加点击事件变更传递给父组件的值,slot部分的item也就会接收到该值。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值