Home > front end >  How to pass an object as props with Vue Router with Vue 3?
How to pass an object as props with Vue Router with Vue 3?

Time:01-10

How to pass an object as props in Vue 3 using the Vue Router? This can be achieved in Vue 2 following the accepted answer here and its corresponding JSFiddle. In Vue 3 this syntax stringifies pushed objects into "[object Object]" in contrast to Vue 2. I have tried with Vue 3 in the following fiddle.

const Home = { template: '<div>Home</div>',
               mounted: function() {
                this.$router.push({
                    name: "about",
                    params: {
                        user: "User Name",
                        objectParam: {a: "a"}
                    }
                  })
                }}
const About = { template: '<div>About</div>',
                                props: ['user', 'o', 'objectParam'],
                mounted: function(){
                    console.log( "Passed props:" )
                    console.log( this.$props )
                }}

const routes = [
  { path: '/', component: Home },
  { path: '/about', name:"about", component: About, 
                                  props: route => (
                                         console.log("Params defined here are passed as objects."),
                                         console.log("But route params object passed via push has already been stringified."),
                                         console.log(route.params),
                                         {o: {b: "b"},
                                          ...route.params
                                          })},
]


const router = VueRouter.createRouter({
  history: VueRouter.createWebHashHistory(),
  routes,
})

const app = Vue.createApp({})
app.use(router)
app.mount('#app')

Can objects be passed via Vue Router push() in Vue 3?

CodePudding user response:

I can't find any official documentation from Vue Router to support that and to be honest I don't think it's a great idea to send dynamic objects as params, but if you really want to do so, one way to achieve it is to stringify your object and then parse it on the receiver side. So something like this:

this.$router.push({
    name: "about",
    params: {
        user: "User Name",
        objectParam: JSON.stringify({ a: "a" })
    }
})

And then in the other component:

JSON.parse(this.$route.params.objectParam)

CodePudding user response:

I'm going out on a limb and saying I don't think that's possible in Vue3.

You might take a look into a state manager like Vuex and see if it solves your problem. The state manager concept will allow you to keep a complex object across multiple views.

  •  Tags:  
  • Related