0

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 Answers 2

2

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()
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.