Getting URL Route Parameters in Vue 3

2023年12月6日 3810点热度 0人点赞 0条评论
内容目录

First, create the corresponding routes in router/index.ts.


const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView
    },
    {
      path: '/datasource/:source?/:database?',
      name: 'dataSource',
      component: DataSource
    }
  ]
})

export default router

In the .vue file, import:

import { useRoute, useRouter } from 'vue-router';
// For route recognition
const route = useRoute();
// For route redirection
const router = useRouter();

To get the route parameters of the page:

console.log("Page route parameters:");
console.log(route.params);

When you open http://localhost:5173/aaa/bbb on the page, you can use route.params.source and route.params.database to obtain the parameters. If you are dealing with query parameters, you can use route.query.

If the user clicks a button and wants to display that address in the URL, you can use:

router.push({ name: 'dataSource', params: { source: 'aaa', database: 'bbb' } });  

痴者工良

高级程序员劝退师

文章评论