乐趣区

关于前端:记录Vue3移动端手势滑动封装

1、Hooks 封装

import {ref} from 'vue';
import linkHooks from '@/hooks/linkTo';

/* 参数 1:右边路由;参数 2:左边路由;参数 3:绑定的 DOM 元素 */
export default function(left,right,dom){const [flag, startX, endX,isshow] = [ref(false), ref(0), ref(0),ref(false)]
   const {linkTo} = linkHooks()

   function start(e) {  // 记录开始滑动屏幕的 X 轴的地位
      flag.value = true;
      startX.value = e.touches[0].clientX;
      endX.value = dom.value.offsetLeft;
   }

   function end(e) {if (flag.value) {
         flag.value = false;
         const moveX = e.changedTouches[0].clientX - startX.value;  // 计算滑动的间隔
         if (moveX < -80) {
            isshow.value = true;
            linkTo(right)
         } else if (moveX > 80) {
            isshow.value = true;
            linkTo(left)
         }
      }
   }

   return {
      start,
      end,
   }
}

2、组件中应用

<script setup>
import slideHooks from '@/hooks/slide';
const {start,end} = slideHooks('Separation','meeting',destroy)
</script>

<template>
 <div class="meeting width" ref="destroy" @touchstart="start($event)" @touchend="end($event)"></div>
</template>
退出移动版