今天在项目中使用vant 的SwipeCell 滑动单元格实现左滑删除购物车的效果,精简后的代码如下
<view wx:for="{{cart}}" wx:key="id">
<van-swipe-cell right-width="{{ 65 }}" bind:open="onOpen">
<van-cell-group>
<van-cell title="{{item.title}}" value="{{item.value}}" />
</van-cell-group>
<view slot="right" class="right" bindtap="onDelete" data-id="{{item.id}}">删除</view>
</van-swipe-cell>
</view>
.right{
background-color: red;
height: inherit;
width: 65px;
color: white;
display: flex;
align-items: center;
justify-content: center;
}
Page({
data: {
cart: [
{ id: "001", title: "iPhone", value: "手机" },
{ id: "002", title: "MacBook", value: "笔记本" },
{ id: "003", title: "AirPods", value: "耳机" },
],
},
onDelete() {
console.log("delete", event.target.dataset.id);
},
onOpen() {
console.log("open");
},
});
但问题出现了:点击空白位置没法自动关闭
查了一番发现确实官方没有提供该功能,而且有人遇到过类似问题
https://github.com/youzan/vant-weapp/issues/4660
https://blog.youkuaiyun.com/pannikin/article/details/118526160
最后解决的思路是在open的时候将该单元格的实例存入变量中,在响应点击事件时,将变量中的实例逐个调用实例方法close
代码如下:
<!-- cart/cart.wxml -->
<view class="page-view" bindtap="onTap">
<view wx:for="{{cart}}" wx:key="id">
<van-swipe-cell id="wx{{item.id}}" right-width="{{ 65 }}" data-id="{{item.id}}" bind:open="onOpen">
<van-cell-group>
<van-cell title="{{item.title}}" value="{{item.value}}" />
</van-cell-group>
<view slot="right" class="right" bindtap="onDelete" data-id="{{item.id}}">删除</view>
</van-swipe-cell>
</view>
</view>
page{
height: 100%;
}
.page-view{
height: 100%;
}
.right{
background-color: red;
height: inherit;
width: 65px;
color: white;
display: flex;
align-items: center;
justify-content: center;
}
Page({
data: {
cart: [
{ id: "001", title: "iPhone", value: "手机" },
{ id: "002", title: "MacBook", value: "笔记本" },
{ id: "003", title: "AirPods", value: "耳机" },
],
selected: [],
},
onDelete(event) {
console.log("delete", event.target.dataset.id);
},
onOpen(event) {
console.log("open");
// 根据id选择instance
let instance = this.selectComponent(`#${event.target.id}`);
this.data.selected.push(instance);
},
onTap() {
console.log("tap");
// 循环关闭
this.data.selected.forEach(function (instance) {
instance.close();
});
// 清空
this.data.selected = [];
},
});
你会发现在获取实例的过程中,是通过元素的id配合使用this.selectComponent方法进行查找,而元素id则是在渲染的时候使用业务数据中的id。之所以要这么做,全是因为open事件的参数中没有instance,如果有的话就可以这么写
...
onOpen(event) {
const { position, instance } = event.detail;
this.data.selected.push(instance);
},
...
可惜这只是一厢情愿,官方并不支持
参考:https://youzan.github.io/vant-weapp/#/swipe-cell