event handler directive for Vue.
用来防止事件重复执行的 Vue 指令
demo: demo.html
// yarn
yarn add vue-handler-directive
// or npm
npm i vue-handler-directive -S
import Vue from 'vue'
import VHandler from 'vue-handler-directive'
Vue.use(VHandler)
<template>
<div>
<!-- default 默认事件触发 -->
<button v-handler="handler">Default</button>
<!-- arguments 带参数的 handler -->
<button v-handler="(e) => handlerWithArgs(1, 2)">Handler with Arguments</button>
<!--
promise:
when the handler function returns a promise, handler will run on next click after promise is resolved or rejected
当 handler 函数返回 promise 时,在 timeout 超时并且 promise 状态 resolved 或者 rejected 后,才能再次触发执行 handler(使用 async/await 代码更简洁)
-->
<button v-handler="handlerPromise">Handler return Promise</button>
<!-- stop 停止冒泡 -->
<div class="container" @click="containerClick">
<button v-handler.stop="handler">Stop Propagation</button>
</div>
<!-- prevent 阻止默认 -->
<a href="https://www.baidu.com" target="_blank" v-handler.prevent="handler">Prevent Default</a>
<!-- timeout 超时时间 -->
<button v-handler="{ handler: handler, timeout: 3000 }">Timeout 3s</button>
<!-- pendingAttr 等待状态元素属性,默认 pending -->
<button v-handler="{ handler: handler, pendingAttr: 'loading' }">Pending Attribute</button>
<!--
disabled:
handler will not run
handler 在元素 disabled 时不执行
-->
<a disabled v-handler="handler">Disabled Element</a>
<!-- event: v-handler:eventName 其他事件 -->
<button v-handler:contextmenu.prevent="handler">Contextmenu</button>
<button v-handler:touchstart="handler">Touchstart</button>
</div>
</template>
<script>
export {
methods: {
// handler
handler (e) {
const btn = e.target.innerText
console.log('Event: "'+ e.type +'" Button: "'+ btn + '"')
},
// promise
handlerPromise (e) {
const vm = this
const btn = e.target.innerText
return new Promise (function (resolve, reject) {
setTimeout(function () {
console.log('Event: "'+ e.type +'" Button: "'+ btn + '"')
resolve()
}, Math.random() * 5000)
})
},
// handler with arguments
handlerWithArgs (arg1, arg2) {
const args = Array.prototype.slice.call(arguments, 1).join()
console.log('Arguments: "'+ args +'"')
},
containerClick () {
console.log('container clicked!')
}
}
}
</script>