如何阻止<router-link>将用户发送到另一个页面?

ale*_*lex 6 vue.js vuejs2

我有一个这样的逻辑:是用户是V2使用用户到url中subHeaderRouter.router.如果用户未启动this.openModal:

<router-link
  v-for="subHeaderRouter in subHeaderRouters"
  :to="subHeaderRouter.router"
  @click="handleOpenModal()">
</router-link>

handleOpenModal () {
  if (this.IsV2User) return
  this.openModal('changeUserType', 'user.changeUserType')
}
Run Code Online (Sandbox Code Playgroud)

我现在唯一需要做的就是停止:to用户不是V2.怎么做到这一点?

Dec*_*oon 15

您可以<router-link>通过指定无事件来监听和click手动处理事件来阻止默认行为:

<router-link
  v-for="subHeaderRouter in subHeaderRouters"
  event=""
  :to="subHeaderRouter.router"
  @click.native.prevent="handleOpenModal(subHeaderRouter.router)"/>
Run Code Online (Sandbox Code Playgroud)
handleOpenModal(route) {
    if (this.IsV2User) {
        this.$router.push(route)
    } else {
        this.openModal('changeUserType', 'user.changeUserType')
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢。你一定是 Vue 老手。 (5认同)

UX *_*dre 9

Vue 3 解决方案

在 Vue3 中,event已从中删除"<router-link>,您将需要使用v-slot API代替。


 <router-link :to="yourRoute" custom v-slot="{ href, navigate }">
    <a v-if="yourBoolean" @click="handleEvent()">Run the function</a>
    <a
        v-else
        :href="href"
        @click="navigate">
        Go to route in "to"
    </a>
</router-link>
Run Code Online (Sandbox Code Playgroud)

// Vue 3 Composition API

export default {  
    setup() {
        const handleEvent = () => {
            
           // Add your logic here
      
        }
    }
};
Run Code Online (Sandbox Code Playgroud)