uni-app nvue页面 长按事件 longpress 会穿透小盒子中的点击事件

uni-app nvue页面 长按事件 longpress 会穿透小盒子中的点击事件

示例代码:

<view class="comment-list-info-title-mian" @touchstart="itemTouchstart" @touchmove="itemTouchmove" @longpress="moreIncident(item,idx)">
    <text class="comment-list-info-title" @tap.stop="toInfo(item,1)">{{item.user_nickname}}</text>
    <text v-if="item.is_author" class="comment-list-info-author">作者</text>
</view>

操作步骤:

  • 长按某元素 长按事件开始执行 盒子中的点击事件也被执行了

预期结果:

  • 长按事件执行 点击事件不执行

实际结果:

  • 长按事件开始执行 点击事件也被执行了

bug描述:

nvue页面 在点击事件外层盒子价格longpress长按事件 长按执行后 点击事件也执行了


更多关于uni-app nvue页面 长按事件 longpress 会穿透小盒子中的点击事件的实战教程也可以访问 https://www.itying.com/category-93-b0.html

11 回复

大佬们 长按事件有没有阻止冒泡的方法

更多关于uni-app nvue页面 长按事件 longpress 会穿透小盒子中的点击事件的实战教程也可以访问 https://www.itying.com/category-93-b0.html


你好,请问这个问题解决了吗?

回复 c***@163.com: 没有

回复 特购: 解决了嘛

回复 [已删除]: 没有

回复 特购: 我现在是用个全局变量来控制

这么严重的问题就这么沉了吗

这只能算很普通的问题。。你看看我个人中心关注的那些~

回复 f***@outlook.com: 哎 好心累啊

确实累啊

在 nvue 页面中,由于原生渲染机制与 WebView 不同,事件处理确实存在差异。longpress 事件触发后,会继续触发子元素的 tap 事件,这是 nvue 的默认行为。

要解决 longpress 事件穿透导致子元素 tap 被触发的问题,可以通过以下方式:

  1. 使用 @touchstart@touchend 手动模拟长按:通过记录触摸开始时间,计算时间差来判断是否为长按,并在长按时阻止事件冒泡。

    示例:

    <view 
        @touchstart="handleTouchStart"
        @touchend="handleTouchEnd">
        <text @tap="toInfo">点击我</text>
    </view>
    
    data() {
        return {
            touchTimer: null
        };
    },
    methods: {
        handleTouchStart() {
            this.touchTimer = setTimeout(() => {
                // 执行长按逻辑
                this.moreIncident();
            }, 500); // 设置长按时间阈值,例如500ms
        },
        handleTouchEnd() {
            clearTimeout(this.touchTimer);
        }
    }
    
  2. longpress 事件中阻止事件冒泡:虽然 nvue 的 longpress 事件不支持 .stop 修饰符,但可以在事件处理函数中手动调用 stopPropagation 方法(需注意 nvue 中事件对象的兼容性)。

    示例:

    <view [@longpress](/user/longpress)="handleLongPress">
        <text @tap="toInfo">点击我</text>
    </view>
    
    methods: {
        handleLongPress(e) {
            // 执行长按逻辑
            this.moreIncident();
            // 尝试阻止事件冒泡
            if (e.stopPropagation) {
                e.stopPropagation();
            }
        }
    }
    
  3. 通过条件判断屏蔽点击事件:在 tap 事件处理函数中,通过标志位判断是否刚触发过长按事件,如果是则忽略 tap

    示例:

    data() {
        return {
            isLongPress: false
        };
    },
    methods: {
        moreIncident() {
            this.isLongPress = true;
            // 执行长按逻辑
            // 在逻辑执行后重置标志位,例如使用 setTimeout
            setTimeout(() => {
                this.isLongPress = false;
            }, 300);
        },
        toInfo() {
            if (this.isLongPress) return;
            // 执行点击逻辑
        }
    }
回到顶部