如何防止/停止指令(vue 2.x)中默认事件(点击)的传播 [英] How to prevent/stop propagation of default event (click) in directive (vue 2.x)
问题描述
Vue.directive('login-to-click', {
bind (el) {
const clickHandler = (event) => {
event.preventDefault()
event.stopImmediatePropagation()
alert('click')
}
el.addEventListener('click', clickHandler, true)
}
})
使用
<button @click="handleClick" v-login-to-click>CLICK</button>
handleClick
总是被触发.我怎样才能防止这种情况发生?尝试使用/不使用 addEventListener捕获"标志但没有任何运气.
handleClick
is always triggered. How I can prevent that from directive? Tried with/without addEventListener "capture" flag without any luck.
现在我最终得到了以下解决方案:
For now I ended up with following solution:
Vue.prototype.$checkAuth = function (handler, ...args) {
const isLoggedIn = store.getters['session/isLoggedIn']
if (isLoggedIn) {
return handler.apply(this, args)
} else {
router.push('/login')
}
}
然后在组件中
<button @click="$checkAuth(handleClick)">CLICK</button>
推荐答案
根据我的理解,这是两个不同的事件处理程序,您只是在阻止指令中绑定的默认事件,这对 没有影响@click
但是,因为您没有覆盖点击侦听器,而是添加了第二个侦听器.如果您希望阻止默认的 @click 绑定,您可以使用 @click.prevent="handleClick"
.
From my understanding those are two different event handlers, you are only preventing the default event of the one bound in the directive, this has no influence on @click
however, because you are not overwriting the click listener but adding a second one.
If you want the default of your @click binding to be prevented you can use @click.prevent="handleClick"
.
我不认为有任何方法可以从指令中做到这一点,因为您通过将 @click
绑定到按钮来显式添加另一个侦听器.
I don't think there's any way to do it from the directive, since you explicitly add another listener by binding @click
to the button.
这篇关于如何防止/停止指令(vue 2.x)中默认事件(点击)的传播的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!