Vue.directive('login-to-click', {
bind (el) {
const clickHandler = (event) => {
event.preventDefault()
event.stopImmediatePropagation()
alert('click')
}
el.addEventListener('click', clickHandler, true)
}
})
usage
<button @click="handleClick" v-login-to-click>CLICK</button>
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')
}
}
And then in component
<button @click="$checkAuth(handleClick)">CLICK</button>
You can use:
I am not sure why would want to do that though, since you are adding a click listener for a reason.
Perhaps you could clarify your question a bit more.
In my case, I need to conditionally prevent the default behavior of the right and left arrow keys. While the cursor is in the middle of my input field, I want the normal behavior of the event to move the cursor. However, when I reach the beginning or end of the input I want the focus to change to the next input and position the cursor at the beginning of the next field for a right arrow and at the end of the next field for a left arrow. When I position the cursor at the beginning or end of the next field the default left or right event behavior gives me a "one off" effect. This occurs because the left or right arrow key event can finish it's default behavior after I change the focus and set the cursor location.
In my case "event.target.preventDefault()" didn't stop the default behavior. I used "event.preventDefault()" to prevent the default behavior of the event:
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"
.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.As with many things in Vue 2, this is a bad use case for a directive, but a very good use case for a component.
Here is a button that is only clickable when the user is authorized.
With this button you can set an authorized handler and a non-authorized handler. Additionally, you can just disable the button if the user is not authorized.
In this component the authorized state is passed in through a property, but if you were using some form of state management (like Vuex) you could just as easily use that instead.