uni-app vue2模态框中@touchmove.stop事件失效

uni-app vue2模态框中@touchmove.stop事件失效

1 回复

更多关于uni-app vue2模态框中@touchmove.stop事件失效的实战教程也可以访问 https://www.itying.com/category-93-b0.html


uni-app 中使用 Vue 2 开发时,如果在模态框(Modal)中使用了 @touchmove.stop 事件来阻止触摸滚动,但发现事件失效,可能有以下几种原因和解决方案:

1. 事件冒泡问题

@touchmove.stop 是通过 event.stopPropagation() 来阻止事件冒泡的。如果模态框内部有子元素并且它们的 touchmove 事件没有被阻止,事件仍然会冒泡到父元素,导致模态框滚动。

解决方案: 确保模态框内部的所有子元素的 touchmove 事件都被阻止。你可以为每个子元素都添加 @touchmove.stop,或者在模态框的根元素上添加 @touchmove.stop

<template>
  <div class="modal" @touchmove.stop>
    <div class="modal-content">
      <!-- 模态框内容 -->
    </div>
  </div>
</template>

2. 事件绑定位置问题

如果你在模态框的某个子元素上绑定了 @touchmove.stop,但模态框的其他部分仍然可以滚动,可能是因为事件绑定位置不正确。

解决方案: 确保 @touchmove.stop 绑定在模态框的根元素上,而不是某个子元素。

<template>
  <div class="modal" @touchmove.stop>
    <div class="modal-header">
      <!-- 模态框头部 -->
    </div>
    <div class="modal-body">
      <!-- 模态框内容 -->
    </div>
    <div class="modal-footer">
      <!-- 模态框底部 -->
    </div>
  </div>
</template>

3. 样式问题

如果模态框的样式设置不当,可能会导致 @touchmove.stop 失效。例如,如果模态框的内容区域设置了 overflow: scroll 或者 overflow-y: scroll,可能会导致滚动事件无法被阻止。

解决方案: 确保模态框的样式设置正确,避免在模态框内容区域使用 overflow: scroll 或者 overflow-y: scroll

.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-content {
  background-color: white;
  padding: 20px;
  border-radius: 10px;
  max-height: 80vh;
  overflow: hidden; /* 确保内容不会溢出 */
}

4. 使用 preventDefault

在某些情况下,stopPropagation 可能无法完全阻止滚动行为。你可以尝试使用 preventDefault 来阻止默认的滚动行为。

解决方案: 在手势事件中使用 event.preventDefault() 来阻止默认的滚动行为。

<template>
  <div class="modal" @touchmove="handleTouchMove">
    <div class="modal-content">
      <!-- 模态框内容 -->
    </div>
  </div>
</template>

<script>
export default {
  methods: {
    handleTouchMove(event) {
      event.preventDefault();
      event.stopPropagation();
    }
  }
}
</script>

5. 使用 catchtouchmove

uni-app 提供了一个 catchtouchmove 事件,它可以捕获并阻止所有的 touchmove 事件。

解决方案: 使用 catchtouchmove 来阻止模态框的滚动。

<template>
  <div class="modal" catchtouchmove>
    <div class="modal-content">
      <!-- 模态框内容 -->
    </div>
  </div>
</template>
回到顶部