简体   繁体   中英

How to pass props in vue router

Hi guys i been trying to pass props in vue routes so far i was able to achieve this below, but is not what i wanted.

So far this works

route.js

{
    path: '/register/',
    name: 'register',
    component: require('./views/Login').default,
}

home.vue

<router-link tag="li" :to="{ name: 'register', params: { isRegisteringMe: 'true' }}" class="btn btn-green m-top-20 menu-btn" v-show="!isLoggedIn">Register</router-link>

And in register.vue i can console.log(this.$route.params.isRegisteringMe); which will return true when i click on Register link.

This is fine but what happen is user wants to type in the url directly website.com/register this method will not work. So i try several method but still not getting no where when i write this below.

{
    path: '/register/:id',
    name: 'register',
    props: { isRegisteringMe: 'hi props'},
    component: require('./views/Login').default,
}

Or

{
    path: '/register',
    name: 'register',
    props: { isRegisteringMe: 'hi'},
    params: { isRegisteringMe: 'hi'},
    component: require('./views/Login').default,
}

Trust me i tried many different combination but i am still stuck.

I think you have some misconception about the usage of params in vue-router. Params should be part of the path.

for eg, if the path setting is like

{
    path: '/register/:id',
    // ...
}

<router-link :to="{ name: 'register', params: { id: 'abc123', isRegisteringMe:'true' }}">Register</router-link> will link the user to register/abc123 .

since the path setting is path: '/register/:id', , isRegisteringMe param is not defined and won't be displayed in the url.

Params should be part of the path. I see a few way you can change this.

  1. use url query for isRegisteringMe . for eg, /register?isRegisteringMe=true ( <router-link :to="{ name: 'register', query: { isRegisteringMe: 'true' }}" ). and get the value from $route.query.isRegisteringMe

update:

if you want user to always have isRegisteringMe:true by default do a redirection in register component's mounted lifecycle event.

  1. set isRegisteringMe in the app's state, or preferably in vuex if you are using it. then in register component, get the state and use it accordingly.

hope that this move you towards the right direction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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