简体   繁体   English

如何使用Vue指令防止链接或按钮中的点击事件

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

Hi I'm playing around with vue directives and I'm trying to prevent click event if the element is <a> or <button> tag.嗨,我正在使用 vue 指令,如果元素是<a><button>标记,我正在尝试阻止单击事件。 So my question is, is this possible to do using vue directive?所以我的问题是,这可以使用 vue 指令吗?

Html html

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

Vue directive Vue 指令

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
                }
            }
        }
    }
}

Vue registers the @click event first before v-noclick where you add a second click event listener on that element. Vue 在v-noclick之前首先注册@click事件,您可以在该元素上添加第二个单击事件侦听器。 When the <a> is clicked, the displayModal() function will be executed first, then the listener in the v-noclick directive will be executed.当点击<a> ,将首先执行displayModal()函数,然后将执行v-noclick指令中的侦听器。 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()
  }
}

i couldn't find a vue way to do this.我找不到一种 vue 方法来做到这一点。 but with js you can use conditional sequence like this但是使用 js 你可以使用这样的条件序列

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

in this case if cond be equals to true then onClick will called在这种情况下,如果 cond 等于 true 然后 onClick 将调用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM