Question:
How can I pass an Object as param to the router in VueJS 3 (Composition API + script setup)?

Problem:

In this project, there's the user which is a js object, like this:


const user = {

 "ID": id,

 "NAME": name, 

 "EMAIL": email,

 ...

}


And here's the router on VueJS:

    path: '/home/:user',

    component: Home      

},


But this won't work of course, it expects a String, not a Object. It would be annoying transform this URL to hold all params, like this: path: '/home/:id/:name/:email/:etc...' because the object has lots of attributes and perhaps there'll be another objects to pass to routes.


Is there a simple way to solve this issue?


Solution:

Try the following steps:


  1. Serialize the user object into a JSON string when navigating to the route:

const navigateToHome = () => {

  router.push({ name: 'home', params: { user: JSON.stringify(user) } })

}


  1. Configure your router to accept the serialized user object as a parameter:

import { createRouter, createWebHistory } from 'vue-router'


const routes = [

  {

    path: '/home/:user',

    name: 'home',

    component: Home,

    props: route => ({

      user: JSON.parse(route.params.user)

    })

  },

  // ... other routes

]


const router = createRouter({

  history: createWebHistory(),

  routes

})


export default router


you might want to check the vue router link in the function mode section: >https://router.vuejs.org/guide/essentials/passing-props.html#Function-mode


Suggested blogs:

>How To Create Nested Table Structure In Angular?

>How to Create_function deprecated in PHP?

>How to delete duplicate names from Array in Typescript?

>How to do PHP Decryption from Node.js Encryption

>How to Set up the Android Emulator

>How to Set up the local environment for Angular development?

>How to solve encoding issue when writing to a text file, with Python?


Nisha Patel

Nisha Patel

Submit
0 Answers