zodream梦想开源/个人编程日记

zodream梦想开源/个人编程日记

简单的个人编程日记

马上订阅 zodream梦想开源/个人编程日记 RSS 更新: https://zodream.cn/blog/rss

vue 实现左滑删除

2019年3月15日 00:46
编程技术

更新

支持 :index 为数值或字符串

演示效果

源码

实现原理

  1. 需要记录初始位置,滑动方向,是否是滑动(点击不触发touchmove事件)

oldLeft: 0,       // 记录初始位置 > 0 显示左边控件 < 0 显示右边控件  0 原始状态
left: 0,         // 控制滑动位置
startX: 0,       // 记录滑动的初始位置
isTouch: false,  //判断是否是滑动


touchStart(e: TouchEvent) {
    this.oldLeft = this.left;
    this.isTouch = false;
    this.startX = e.targetTouches[0].clientX;
},
  1. 滑动中不能超过可显示的隐藏区域宽度

touchMove(e: TouchEvent) {
    this.isTouch = true;
    // 获取滑动距离
    const diff = e.targetTouches[0].clientX - this.startX;
    if (this.oldLeft == 0) {
        if (diff < 0) {
            // 左滑显示右边控件
            this.left = Math.max(diff, -this.getRightWidth());
            return;
        }
        // 右滑显示左边控件
        this.left = Math.min(diff, this.getLeftWidth());
        return;
    }
    if (this.oldLeft > 0) {
        if (diff > 0) {
            // 已显示左边控件,不能继续右滑
            return;
        }
        // 左滑隐藏左边控件
        this.left =  Math.max(this.oldLeft + diff, 0);
        return;
    }
    if (diff < 0) {
        // 已显示右边控件,不能继续左滑
        return;
    }
    // 右滑隐藏右边控件
    this.left = Math.min(this.oldLeft + diff, 0);
}
  1. 滑动结束,判断总滑动距离,不超过1/3自动复原

touchEnd(e: TouchEvent) {
    if (!this.isTouch) {
        // 点击,并复原
        this.animation(this.left, 0);
        this.$emit('click');
        return;
    }
    if (this.left == 0) {
        return;
    }
    if (this.left > 0) {
        const width = this.getLeftWidth();
        this.animation(this.left, this.left * 3 > width ? width : 0);
        return;
    }
    const width = - this.getRightWidth();
    this.animation(this.left, this.left * 3 < width ? width : 0);
}
  1. 点击事件需要复原

关于操作一个隐藏其他实现设想

  1. 通过父控件记录所有子控件引用,并标记子空间顺序,在父控件调用子元素复原方法或子控件内部调用

  2. 子控件在初始化的时刻,生成一个自增唯一标识,然后根据这个挂载到父控件或全局属性上

完整代码


<template>
    <div class="swipe-row" :style="{left: left + 'px'}">
        <div class="actions-left" ref="left">...

剩余内容已隐藏

查看完整文章以阅读更多