安装:npm install hammerjs --save
main.js:
import ‘./hammer/index.js’;
hammer/index.js:
import Vue from 'vue';
import Hammer from 'hammerjs';
// https://www.jianshu.com/p/0b0b9364f967
/**
*
* @param {object} el html 元素
* @param {String} type event name
* @param {object} binding 指令后面的值binding对象
* @returns {object} 返回 hammer实例对象
*/
function vueHammerDirective(el, type, binding) {
const hammerCase = new Hammer(el);
hammerCase.on(type, binding.value);
return hammerCase;
}
/**
* 生成hammer指令
* @param {Array|String} hammerEvents hammer 事件数组
* @returns {void} 无返回值
*/
function makeHammerDirective(hammerEvents) {
hammerEvents.forEach((eventName) => {
Vue.directive(eventName, {
inserted(el, binding) {
el.hammerCase = vueHammerDirective(el, eventName, binding);
},
unbind(el) {
el.hammerCase = null;
}
});
});
}
// tap: 点击
// press: 长按
// pan
// panstart: 拖动开始
// panmove: 拖动过程
// panend: 拖动结束
// pancancel: 拖动取消
// panleft: 向左拖动
// panright: 向右拖动
// panup: 向上拖动
// pandown: 向下拖动
// swipe
// swipeleft: 向左滑动
// swiperight: 向右滑动
// swipeup: 向上滑动
// swipedown: 向下滑动
// 按需求自己增加就行
const _hammerEvents = [
'tap', 'press',
'panstart', 'panmove', 'panend', 'pancancel', 'panleft', 'panright', 'panup', 'pandown',
'swipeleft', 'swiperight', 'swipeup', 'swipedown'
];
// 生成hammer指令
makeHammerDirective(_hammerEvents);
在页面中使用:v-tap=“tapCg(item)”
可以在指令中传参,return function
tapCg(item) {
const _this = this;
return function () {
if (!_this.showDelIcon) {
// 可以获取到item
}
};
},