vue自定义tap指令
1.Vue指令
Vue提供自定义实现指令的功能, 和组件类似,可以是全局指令和局部指令,详细可以参见vue官网自定义指令一节(https://cn.vuejs.org/v2/guide/custom-directive.html).
2.v-tap指令实现
我个人的理解,编写指令即是在vue指令对象提供的钩子函数中做相应的逻辑处理,tap指令是在bind钩子函数中做相应的处理, 首先,要明白的是tap是为了处理click事件在iphone上的存在300ms的延时,这样使得连续点击很不流畅,tap通过移动端的touchstart事件和touchend事件判断移动距离为零的话,则触发绑定的函数,话不多说,上代码:
import Vue from 'vue';
function tap(dom, callback) {
/*
* 要求 没有触发 touchmove 事件
* 并且响应速度要比click快
*/
if (dom && typeof dom == 'object') {
var isMove = false;
var startTime = 0;
dom.addEventListener('touchstart', function(e) {
//console.log('touchstart');
//console.time('tap');/*记录tap这个参数现在的时间*/
startTime = Date.now();
});
dom.addEventListener('touchmove', function(e) {
//console.log('touchmove');
isMove = true;
});
dom.addEventListener('touchend', function(e) {
//console.log('touchend');
//console.timeEnd('tap')/*打印tap这个参数距离上一次记录的时候的时间*/
/*判读 是否满足tap 的要求 一般要求tap的响应时间150*/
if (!isMove && (Date.now() - startTime) < 150) {
/*调用 callback*/
// callback && callback(e);
callback.call(dom, e);
}
/*重置 参数*/
isMove = false;
startTime = 0;
});
}
}
Vue.directive('tap', {
bind: function(el, binding) {
tap(el, binding.value)
}
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0" />
<title>自定义tap指令</title>
</head>
<body>
<div id="app">
<button v-tap="todo">按钮</button>
</div>
</body>