目录
一、路由配置
1. 基本路由配置
2. 动态路由配置
3. 可选参数配置
二、路由跳转与传参
1. 声明式导航 (模板中)
2. 编程式导航 (JavaScript中)
三、参数接收
1. 接收动态路由参数
2. 接收查询参数
3. 监听参数变化
四、高级用法
1. 路由元信息
2. 路由守卫控制
3. 动态添加路由
五、完整示例
路由配置示例
组件使用示例
一、路由配置
1. 基本路由配置
// router/index.js
import { createRouter, createWebHistory } from 'vue-router'const routes = [{path: '/',name: 'Home',component: () => import('@/views/Home.vue')},{path: '/about',name: 'About',component: () => import('@/views/About.vue')}
]const router = createRouter({history: createWebHistory(),routes
})export default router
2. 动态路由配置
const routes = [// 动态段以冒号开始{path: '/user/:id',name: 'User',component: () => import('@/views/User.vue')},// 多个动态参数{path: '/post/:postId/comment/:commentId',name: 'PostComment',component: () => import('@/views/PostComment.vue')}
]
3. 可选参数配置
{path: '/user/:id?', // 问号表示可选name: 'UserOptional',component: () => import('@/views/UserOptional.vue')
}
二、路由跳转与传参
1. 声明式导航 (模板中)
<!-- 基本跳转 -->
<router-link to="/about">关于我们</router-link><!-- 动态路由传参 -->
<router-link :to="'/user/' + userId">用户主页</router-link>
<router-link :to="{ name: 'User', params: { id: userId } }">用户主页</router-link><!-- 查询参数传参 -->
<router-link :to="{ path: '/search', query: { keyword: 'vue' } }">搜索</router-link>
2. 编程式导航 (JavaScript中)
import { useRouter } from 'vue-router'const router = useRouter()// 1. 动态路由传参
router.push('/user/123') // 路径方式
router.push({ name: 'User', params: { id: 123 } }) // 命名路由方式// 2. 查询参数传参
router.push({path: '/search',query: {keyword: 'vue',page: 1}
})// 3. 替换当前路由 (不保留历史记录)
router.replace({ path: '/login' })// 4. 前进/后退
router.go(1) // 前进
router.go(-1) // 后退
三、参数接收
1. 接收动态路由参数
import { useRoute } from 'vue-router'const route = useRoute()// 接收单个参数
const userId = route.params.id// 接收多个参数
const postId = route.params.postId
const commentId = route.params.commentId// 可选参数处理
const optionalId = route.params.id || 'default'
2. 接收查询参数
import { useRoute } from 'vue-router'const route = useRoute()// 获取查询参数
const keyword = route.query.keyword
const page = Number(route.query.page) || 1 // 带类型转换和默认值// 处理数组参数 (如 ?tags=vue&tags=js)
const tags = Array.isArray(route.query.tags) ? route.query.tags : [route.query.tags].filter(Boolean)
3. 监听参数变化
import { watch } from 'vue'
import { useRoute } from 'vue-router'const route = useRoute()// 监听动态参数变化
watch(() => route.params.id,(newId) => {console.log('用户ID变化:', newId)fetchUserData(newId)}
)// 监听查询参数变化
watch(() => route.query,(newQuery) => {console.log('查询参数变化:', newQuery)},{ deep: true }
)
四、高级用法
1. 路由元信息
// 路由配置
{path: '/admin',name: 'Admin',component: () => import('@/views/Admin.vue'),meta: {requiresAuth: true,role: 'admin'}
}// 组件中获取
const route = useRoute()
const requiresAuth = route.meta.requiresAuth
2. 路由守卫控制
router.beforeEach((to, from, next) => {if (to.meta.requiresAuth && !isAuthenticated()) {next({path: '/login',query: { redirect: to.fullPath }})} else {next()}
})
3. 动态添加路由
// 添加单个路由
router.addRoute({path: '/new-route',name: 'NewRoute',component: () => import('@/views/NewRoute.vue')
})// 添加嵌套路由
router.addRoute('Admin', {path: 'settings',name: 'AdminSettings',component: () => import('@/views/AdminSettings.vue')
})
五、完整示例
路由配置示例
// router/index.js
import { createRouter, createWebHistory } from 'vue-router'const routes = [{path: '/',name: 'Home',component: () => import('@/views/Home.vue')},{path: '/product/:id',name: 'Product',component: () => import('@/views/Product.vue'),props: true // 将params作为props传递},{path: '/search',name: 'Search',component: () => import('@/views/Search.vue')},{path: '/login',name: 'Login',component: () => import('@/views/Login.vue'),meta: {guestOnly: true}}
]const router = createRouter({history: createWebHistory(),routes
})// 全局路由守卫
router.beforeEach((to, from, next) => {const isAuth = localStorage.getItem('token')if (to.meta.guestOnly && isAuth) {next({ name: 'Home' }) // 已登录用户不能访问登录页} else {next()}
})export default router
组件使用示例
<script setup>
import { useRouter, useRoute } from 'vue-router'
import { onMounted, watch } from 'vue'const router = useRouter()
const route = useRoute()// 编程式导航
const navigateToProduct = (id) => {router.push({name: 'Product',params: { id },query: { from: 'home' }})
}// 接收参数
const productId = route.params.id
const searchQuery = route.query.q// 监听参数变化
watch(() => route.params.id,(newId) => {console.log('产品ID变化:', newId)fetchProduct(newId)}
)// 接收props形式的参数 (需要路由配置 props: true)
const props = defineProps({id: String
})
</script><template><div><!-- 声明式导航 --><router-link :to="{ name: 'Product', params: { id: 123 }, query: { from: 'home' } }">产品123</router-link><!-- 编程式导航按钮 --><button @click="navigateToProduct(456)">查看产品456</button><!-- 显示当前路由参数 --><p>当前产品ID: {{ productId }}</p><p v-if="route.query.q">搜索词: {{ searchQuery }}</p></div>
</template>
总结
-
路由配置:使用
createRouter
创建路由,createWebHistory
创建历史模式 -
动态路由:使用
:param
语法定义动态段 -
跳转方式:
-
声明式:
<router-link>
-
编程式:
router.push()
/router.replace()
-
-
传参方式:
-
动态参数:
params
-
查询参数:
query
-
-
参数接收:使用
useRoute()
获取当前路由信息 -
高级功能:路由守卫、元信息、动态路由添加等
按照这些方法,可以灵活地在 Vue3 项目中实现各种路由需求。