返回
学妹问我微信小程序左滑删除怎么实现?我来详细说一下
前端
2023-09-10 06:14:09
在上篇文章中,我记录了小程序的自定义导航栏的实现过程和小程序基础组件 cover-image 中 使用 fiexd 失效的坑。前天突然在qq上看到一个学妹在群里@我问我小程序怎么实现左滑删除,今天正好有时间就来写一下这个。
左滑删除,严格来说其实就是咱们前面讲过的**自定义组件** ,只不过这次我们需要这个组件支持左滑功能并调用删除函数。
左滑删除需要添加自定义组件<br> 首先在需要使用删除功能的页面对应的json文件中,添加自定义组件,如下图,需要特别注意的是自定义组件的路径相对于组件所在的页面的,这个目录结构和组件在项目中的路径并不相关,无论怎样custom-component的路径都是相对的,即在config/pages.json文件中添加customComponents,而组件所在的位置在component目录下。
```json
"customComponents": [
"list-item"
],
```
然后在component目录下创建list-item.wxml文件
```xml
<view class="list">
<view class="list-item-delete-btn" data-id="{{item.id}}" bindtap="deleteItem">
<text>删除</text>
</view>
<view class="list-item-content">{{item.content}}</view>
</view>
```
```css
.list{
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
background-color: #fff;
padding: 10px;
margin: 10px 0;
}
.list-item-delete-btn{
width: 60px;
height: 60px;
background-color: #f00;
color: #fff;
line-height: 60px;
text-align: center;
}
.list-item-content{
flex: 1;
margin-left: 10px;
}
```
```js
Component({
properties: {
item: {
type: Object,
value: {}
}
},
methods: {
deleteItem(e){
console.log('id', e.currentTarget.dataset.id)
}
}
})
```
最后就是在页面中调用自定义组件
```html
<list-item item="{{item}}" wx:for="{{list}}" wx:key="*this"></list-item>
```