Home » vue » How to prevent click event in link or button using Vue directive

How to prevent click event in link or button using Vue directive

Posted by: admin November 26, 2021 Leave a comment


Hi I’m playing around with vue directives and I’m trying to prevent click event if the element is <a> or <button> tag. So my question is, is this possible to do using vue directive?


    I'm a link

Vue directive

Vue.directive('noclick', {
    bind( elem, binding, vnode ) {

        let user = {'name': 'John Doe'}

        if( user ) {
            let hasAccess = false

            if( !hasAccess ) {
                if( elem.tagName === 'A' ) {
                    elem.addEventListener( 'click', ( event ) => {
                        //this should prevent the element on click event
                        //but not working

                        return false
                    return true

Vue registers the @click event first before v-noclick where you add a second click event listener on that element. When the <a> is clicked, the displayModal() function will be executed first, then the listener in the v-noclick directive will be executed. If the listeners were registered in the opposite order, then it would probably work.

That aside though, it doesn’t look like what you are trying to do should be done inside a custom directive. Instead you can do the same logic in the click handler itself:

<a @click="onClick">Foo</a>
onClick() {
  if (whatever) {


i couldn’t find a vue way to do this. but with js you can use conditional sequence like this

<a @click="cond && onClick"></a>

in this case if cond be equals to true then onClick will called