Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

vue.js

vuejs2

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?

like image 598
alex Avatar asked Jun 29 '17 02:06

alex


2 Answers

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)"/>
like image 70
Decade Moon Avatar answered Oct 05 '22 11:10

Decade Moon


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
      
        }
    }
};
like image 22
Andre W. Avatar answered Oct 05 '22 12:10

Andre W.