alex
alex

Reputation: 7601

How to stop <router-link> from sending the user to another page?

I have a logic like this: is the user is V2 use the user to the url in subHeaderRouter.router. If the user isn't launch 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')
}

The only thing I need to do now is to stop :to then she user is not V2. How to accomplish that?

Upvotes: 21

Views: 19455

Answers (3)

Andre W.
Andre W.

Reputation: 1023

Vue 3 Solution

In Vue3, the event has been removed from "<router-link>, you will need to use v-slot API instead.


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

// Vue 3 Composition API

export default {  
    setup() {
        const handleEvent = () => {
            
           // Add your logic here
      
        }
    }
};

Upvotes: 9

I had the same problem and used dynamic Vue Components as solution. You will also have to check the difference in styling for router and div tag.

<component 
  :is=" condition ? 'router-link' : 'div' "
  @click="handleOpenModal"  
  :to="your_link">
</component>

Upvotes: 0

Decade Moon
Decade Moon

Reputation: 34286

You can prevent the default <router-link> behavior by specifying no default event to listen to and handling the click event manually with the .native modifier:

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

If the event="" seems weird to you, it also works with an empty attribute:

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

Upvotes: 38

Related Questions