Search code examples
vue.jsvuejs2parametersvue-router

Pass props to a route without needing URL params


I want to pass data to a route without needing to define the parameter in the path. I have been able to accomplish passing data by using query params, but I would rather not show the params in the URL.

This is possible for as far as I have found on the internet and documentation of Vue-Router, but I am not 100% sure how to implement this. Thus I would be glad to get some help.

To give you a brief idea, here is the code that I am using:

Cart.vue, the file from where I want to push the router:

this.$router.push({ path: '/checkout', params: {nextUrl: this.$route.fullPath, pid: this.$route.query.pid, quantity: this.quantity }}).catch(() => {});

Checkout.vue, here I would like to retrieve the parameters, for now I am just using console.log and I also put props down (obviously the console.logs are inside a lifecycle hook):

props : ['pid', 'quantity']

console.log(this.$route.params.pid);
console.log(this.$route.params.quantity);

And as last, this is my routing:

{
    path: '/checkout',
    component: Checkout,
    children: [
        {
        // path: '',
        //     component: Personal,
        // }, later afrekenen als gast toevoegen               
            path: '',
            component: Address,
        },
        {
            path: '/checkout/payment',
            component: Payment,
        },                
        {
            path: '/checkout/confirm',
            component: OrderCheck,
        }
    ],
    meta: {
        requiresAuth: true,
    },
    props: true
},

From what I've read, you are able to simply add "props: true" to allow any params to pass? I'm not quite sure, especially because it's returning "undefined" in the console.

Any help would be appreciated, thanks in advance!

UPDATE It works when I change the path: '/checkout' to name: 'checkout' and specifying the name in the routing, but this is not very optimal because it is returning a warning concerning the default child route.

SECOND UPDATE I think I made it work by adding the name 'checkout' to the default child route.


Solution

  • You can do like the following:

    <router-view :some-value="value"/>
    

    And within your component just define the prop:

    props: ["someValue"]
    

    Just note that the prop is getting passed to all routed components, (but is not accessible as long as you don't define the prop).