关于前端:uniapp项目实践总结十自定义滑动触摸组件

3次阅读

共计 2314 个字符,预计需要花费 6 分钟才能阅读完成。

在 APP 的日常凋谢过程中,咱们常常能够看到上拉刷新、下拉刷新、左滑、右滑、触底加载等成果,那其中的原理是如何呢,又是如何实现的呢,上面就一探到底。这篇文章次要是讲述自定义滑动触摸组件的方放,兼容网页 H5 端、微信小程序端和 App 端。

目录

  • 筹备工作
  • 原理剖析
  • 组件实现
  • 实战演练
  • 案例展现

筹备工作

  • components 新建一个 q-swiper 文件夹,并新建一个 q-swiper.vue 的组件;
  • 依照前一篇所说的页面构造,编写好预约的滑动触摸页面;

原理剖析

自定义滑动触摸组件就是采纳一般的办法进行判断滑动上下左右的间隔,从而实现滑动成果。

次要应用到的事件有 ontouchstartontouchendonmousedownonmouseup

依据 pageXpageYclientXclientY来判断滑动方向从而实现滑动性能。

组件实现

筹备工作和原理剖析实现后,接下来写一个简略的自定义滑动模块组件。

模板局部

<view
  class="q-swiper"
  @touchstart="handlerStart"
  @touchend="handlerEnd"
  @mousedown="handlerStart"
  @mouseup="handlerEnd">
  <slot name="content">
    <!-- 插槽自定义内容 -->
  </slot>
</view>

款式局部

.q-swiper {
  width: 100%;
  height: 100%;
}

脚本局部

  • 引入依赖包和属性设置
import {reactive} from "vue";

// 滑动信息
const touchInfo = reactive({
  touchX: "",
  touchY: "",
});

// 滑动类型
const touchTypes = reactive({
  left: {
    id: 1,
    name: "左滑",
    val: "left",
  },
  right: {
    id: 2,
    name: "右滑",
    val: "right",
  },
  up: {
    id: 3,
    name: "上滑",
    val: "up",
  },
  down: {
    id: 4,
    name: "下滑",
    val: "down",
  },
});

// 发送事件
const emits = defineEmits(["change"]);
  • 滑动办法定义
// 滑动开始
function handlerStart(e) {let { clientX, clientY} = e.changedTouches[0];
  touchInfo.touchX = clientX;
  touchInfo.touchY = clientY;
}

// 滑动完结
function handlerEnd(e) {let { clientX, clientY} = e.changedTouches[0];
  let diffX = clientX - touchInfo.touchX,
    diffY = clientY - touchInfo.touchY,
    absDiffX = Math.abs(diffX),
    absDiffY = Math.abs(diffY),
    type = "";
  if (absDiffX > 50 && absDiffX > absDiffY) {type = diffX >= 0 ? "right" : "left";}
  if (absDiffY > 50 && absDiffX < absDiffY) {type = diffY < 0 ? "up" : "down";}
  if (type) {console.log("滑动信息:", touchTypes[type]);
    emits("change", touchTypes[type]);
  }
}

实战演练

写好滑动组件后,能够在 H5、小程序和 App 外面应用了,上面是页面模板和脚本应用办法。

模板应用

<q-swiper @change="changeSwiper">
  <template v-slot:content>
    <view class="swiper-box"> 滑动方向:{{swiperDir.name}} </view>
    <view
      :class="{'swiper-section': true, [swiperDir.val !='click'? swiperDir.val :'']: true}"></view>
  </template>
</q-swiper>

款式编写

.swiper-box {
  padding: 30rpx;
  font-size: 24rpx;
}
.swiper-section {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: #f99;
  opacity: 0.8;
  transition: all 0.5s;
  &.up {transform: translateX(0) translateY(-100%);
  }
  &.down {transform: translateX(0) translateY(0);
  }
  &.left {transform: translateX(0) translateY(0);
  }
  &.right {transform: translateX(100%) translateY(0);
  }
}

脚本应用

鼠标或手指上下左右滑动页面,调用上面办法进行滑动。

  • 定义数据
// 导入依赖
import {reactive} from "vue";

// 滑动方向
let swiperDir = reactive({
  name: "左滑",
  val: "left",
});
  • 办法调用
// 监听事件
function changeSwiper(dir) {
  swiperDir.name = dir.name;
  swiperDir.val = dir.val;
}

案例展现

  • h5 端成果
  • 小程序端成果
  • APP 端成果

最初

以上就是自定义滑动触摸组件的次要内容,有不足之处,请多多斧正。

正文完
 0