0
votes

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?

Html

<a 
    @click.stop.prevent="displayModal()"
    v-noclick="test">
    I'm a link
</a>

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

                        event.stopPropagation()
                        event.preventDefault()
                        event.stopImmediatePropagation()
                        return false
                    })
                    return true
                }
            }
        }
    }
}
2

2 Answers

1
votes

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) {
    this.displayModal()
  }
}
1
votes

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