Vue.directive注册(全局与局部)自定义指令使用详解与实战
warning:
这篇文章距离上次修改已过185天,其中的内容可能已经有所变动。
// 引入Vue
import Vue from 'vue';
// 定义全局自定义指令 `v-focus`,指令的定义函数被调用时,会传入绑定的元素,以及一些其他的信息
Vue.directive('focus', {
// 当绑定元素插入到DOM中时
inserted: function (el) {
// 聚焦元素
el.focus(); // 页面加载时自动聚焦输入框
}
});
// 创建一个Vue实例
new Vue({
el: '#app',
// 局部注册自定义指令 `v-longpress`
directives: {
'longpress': {
bind: function (el, binding, vNode) {
// 确保提供的表达式是函数
if (typeof binding.value !== 'function') {
// 获取组件名称
const compName = vNode.context.name;
let warn = `[longpress:] provided expression '${binding.expression}' is not a function, but has to be`;
if (compName) { warn += `Found in component '${compName}'`; }
console.warn(warn);
}
// 定义变量
let pressTimer = null;
// 创建计时器( 1秒后执行函数 )
let start = (e) => {
if (e.type === 'click' && e.button !== 0) {
return;
}
if (pressTimer === null) {
pressTimer = setTimeout(() => {
// 执行函数
handler(e);
}, 1000);
}
}
// 取消计时器
let cancel = () => {
if (pressTimer !== null) {
clearTimeout(pressTimer);
pressTimer = null;
}
}
// 运行函数
const handler = (e) => {
binding.value(e);
cancel();
}
// 添加事件监听器
el.addEventListener('mousedown', start);
el.addEventListener('touchstart', start);
// 取消计时器
el.addEventListener('click', cancel);
el.addEventListener('mouseout', cancel);
}
}
}
});
这段代码首先引入了Vue库,并定义了一个全局自定义指令v-focus
,该指令在绑定的元素插入DOM时自动聚焦。然后创建了一个Vue实例,并通过directives
选项注册了一个局部自定义指令v-longpress
,该指令在元素长按时触发。代码中对指令的绑定进行了类型检查,并提供了一个警告信息,以帮助开发者调试。
评论已关闭