问题
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.
回答1:
I think you have some misconception about the usage of params in vue-router. Params should be part of the path.
for e.g., 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.
- 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.
- set
isRegisteringMein 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.
来源:https://stackoverflow.com/questions/48940759/how-to-pass-props-in-vue-router