用vue 实现 SwipeCell 组件
时间: 2023-11-20 21:07:24 浏览: 25
SwipeCell 组件一般用于移动端列表滑动操作,可以左右滑动出现操作按钮,下面是一个简单的实现:
首先,我们需要定义 SwipeCell 组件的模板结构,包括左边和右边操作按钮:
```html
<template>
<div class="swipe-cell">
<div class="swipe-cell-content">
<slot></slot>
</div>
<div class="swipe-cell-actions">
<div class="swipe-cell-action" v-for="(action, index) in actions" :key="index">{{ action.text }}</div>
</div>
</div>
</template>
```
接下来,我们需要定义组件的 props 和 data:
```js
export default {
name: 'SwipeCell',
props: {
actions: {
type: Array,
default: () => []
}
},
data() {
return {
startX: 0,
startY: 0,
offsetX: 0,
offsetY: 0,
isMoving: false,
direction: ''
};
}
};
```
其中,props 中的 actions 用于传入左右两个操作按钮的配置,data 中的属性用于记录滑动状态和方向。
接下来,我们需要在组件的 mounted 钩子中绑定 touch 事件:
```js
mounted() {
const contentEl = this.$el.querySelector('.swipe-cell-content');
contentEl.addEventListener('touchstart', this.handleTouchStart);
contentEl.addEventListener('touchmove', this.handleTouchMove);
contentEl.addEventListener('touchend', this.handleTouchEnd);
}
```
然后,我们需要实现 touch 事件的处理函数:
```js
methods: {
handleTouchStart(e) {
this.startX = e.touches[0].pageX;
this.startY = e.touches[0].pageY;
this.offsetX = 0;
this.offsetY = 0;
this.isMoving = true;
},
handleTouchMove(e) {
if (!this.isMoving) return;
const deltaX = e.touches[0].pageX - this.startX;
const deltaY = e.touches[0].pageY - this.startY;
if (Math.abs(deltaX) < Math.abs(deltaY)) {
// 竖向滑动
this.isMoving = false;
return;
}
e.preventDefault();
this.offsetX = deltaX;
this.offsetY = deltaY;
this.direction = deltaX > 0 ? 'right' : 'left';
},
handleTouchEnd() {
if (!this.isMoving) return;
this.isMoving = false;
const threshold = this.$el.offsetWidth / 4;
if (Math.abs(this.offsetX) > threshold) {
this.$emit(`swipe-${this.direction}`);
}
this.offsetX = 0;
this.offsetY = 0;
this.direction = '';
}
}
```
其中,handleTouchStart 函数记录起始位置,handleTouchMove 函数计算偏移量和方向,handleTouchEnd 函数根据偏移量和阈值触发事件。
最后,我们需要对组件进行样式处理:
```css
.swipe-cell {
position: relative;
overflow: hidden;
height: 50px;
background-color: #fff;
.swipe-cell-content {
height: 100%;
display: flex;
align-items: center;
padding: 0 20px;
}
.swipe-cell-actions {
position: absolute;
top: 0;
right: 0;
bottom: 0;
display: flex;
align-items: center;
justify-content: flex-end;
.swipe-cell-action {
width: 60px;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
background-color: #f00;
color: #fff;
font-size: 14px;
&:first-child {
background-color: #0f0;
}
}
}
}
```
这样,我们就完成了 SwipeCell 组件的实现。在使用时,只需要传入左右两个操作按钮的配置即可:
```html
<SwipeCell :actions="[
{ text: '编辑', action: edit },
{ text: '删除', action: del }
]">
<div>这是列表项内容</div>
</SwipeCell>
```