参考:https://www.cnblogs.com/mz-2015/p/9577100.html
1. 安装v-touch: (vue2.0之后的要使用next分支才行,之前的使用master分支即可)
npm insall vue-touch@next --save
2. main.js中引入,注意:这样打包后文件里的vendor.js会引入hammer.js(手势检测)
import VueTouch from 'vue-touch'; Vue.use(VueTouch, { name: 'v-touch' }); VueTouch.config.swipe = { threshold: 10 //手指左右滑动触发事件距离 }
3. 组件中使用:
<template> <div class="hello"> <v-touch @swipeleft="swiperDirection(1)" @swiperight="swiperDirection(2)" class="v-touch wrapper" :class="transClass"> <div class="menu-container" ref="menuContainer"> {{msg}} </div> </v-touch> <div v-show="isLoading" class="modal-loading"><span class="loadingTxt">正在加载中...</span></div> </div> </template> <script> export default { name: 'HelloWorld', data() { return { transClass: '', isLoading: false, msg: '页面1' } }, methods: { swiperDirection: function(i) { //1向左滑2向右滑 let _this = this; if (i == 1) { _this.transClass = 'swipe-left'; } else { _this.transClass = 'swipe-right'; } setTimeout(function() { _this.isLoading = true; _this.getInfo(); }, 500); //因为动画时间需要0.5s }, getInfo() { let _this = this; _this.msg = ''; //可调接口,获取上一条/下一条数据后,再做以下操作 _this.msg = '页面2'; _this.isLoading = false; //不调接口效果可能不明显 _this.transClass = ''; } } } </script> <style scoped>
.v-touch{
touch-action: pan-y !important; //解决页面垂直滚动失效问题
}
.hello, .wrapper, .menu-container, .modal-loading { 100%; height: 100%; } .wrapper { padding-top: 100px; font-size: 20px; background-color: lightcoral; color: #ffffff; } .modal-loading { position: fixed; top: 0; left: 0; color: #ffffff; background-color: rgba(1, 1, 1, 0.8); } .loadingTxt { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } .swipe-left { transition: all 0.5s; transform: translateX(-100%); } .swipe-right { transition: all 0.5s; transform: translateX(100%); } </style>