动态路由的跳转与传参

2022-08-06 VueRoutervue3vite

很多时候,我们需要将给定匹配模式的路由映射到同一个组件。例如,我们可能有一个 User 组件,它应该对所有用户进行渲染,但用户 ID 不同。在 Vue Router 中,我们可以在路径中使用一个动态字段来实现,我们称之为路径参数

路径参数用冒号 : 表示,当一个路由被匹配时,它的 params 的值将在每个组件,5先来看看动态路由是如何定义的:

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView
    },
    {
      path: '/about/:id', // 动态路由,访问地址:http://localhost:5173/about/123456
      name: 'about', // 访问http://localhost:5173/about是无效的
      component: () => import('../views/AboutView.vue')
    }
  ]
})

# 传参方式一

const toDetail = (item) => {
    router.push({
        name: '/about',
        params: {
            id: item.id
        }
    })
}

# 传参方式二

const toDetail = (item) => {
    router.push({
        name: '/about/'+ item.id
    })
}

# 接收参数

import { useRoute } from 'vue-router';
import { data } from './list.json'
const route = useRoute()
const id =  route.params.id
上次更新: 2 年前