Search code examples
vue.jsvue-routervuejs3vue-router4

Pass an object as param to router.push (vue-router@4.05)


Problem

router.push({name:"Order", params: {obj: {}}) fails to push obj: {}, instead the route receives obj: '[object Object]'

Situation

I have a route setup like this

{
    path: '/Order',
    name: 'Order',
    component: () => import("../views/Order.vue"),
    props: route => {
      return route.params.obj //  '[object Object]'
    },
 }

this results in props not being defined in Order.vue

Expected Result

{
    ...
    props: route => {
      return route.params.obj //  '{}'
    },
}

Based on this answer objects work in older versions

What I've tested

I've used jest to inspect the arguments passed to router.push and they appear as they should: {name:"Order", params: {obj: {}}

Any Ideas?


Solution

  • Passing objects to params was never supported in Vue-router

    It sort of worked in Router v3 with $router.push - the target component received the object. BUT as soon as user started using browser navigation (Back button) OR copy/pasting URL's, this solution was broken (you can try it here - just click the button and then use back and forward controls of the frame)

    As a rule of thumb - if you want to pass anything to the target route/component, such data must be defined as parameters in the route definition so it can be included directly in the URL. Alternatives are passing data in a store, query params (objects needs to be serialized with JSON.stringify), or using the history state.

    This was true for Vue-router v3 and is still for Vue-router v4

    Note

    Just to explain alternatives. By "store" I do not mean just Vuex. I understand Vuex can be overkill for some small applications. I personally prefer Pinia over existing Vuex. And you can create global state solution yourself with composition API very easily...