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?
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) } })
}
2.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