Vue3中使用Vue Router,完整详解
简介
Vue Router是Vue.js官方的路由管理器,它和Vue.js核心深度集成,可以快速的构建单页应用。在Vue3中,Vue Router也有了新的变化,本文将会对这些变化进行详细的介绍。
安装Vue Router
在使用Vue Router前,需要先安装它。可以通过npm来安装:
bashCopy Codenpm install vue-router@4 --save
配置Vue Router
在Vue3中使用Vue Router的配置方式发生了一些改变。下面是Vue Router的基本配置:
javascriptCopy Codeimport { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
history: createWebHistory(),
routes: [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
component: About
}
]
})
export default router
可以看到,新的Vue Router使用了createRouter
方法进行实例化,而不再使用Vue2中的new Router
方式。同时,路由的mode
配置被移除,改成了使用createWebHistory
、createWebHashHistory
或createMemoryHistory
方法来进行路由模式的选择。
导航守卫
在Vue Router中,导航守卫是非常重要的一部分,它可以控制路由跳转的过程。Vue3中的导航守卫和Vue2有些不同:
全局前置守卫
javascriptCopy Codeconst router = createRouter({
history: createWebHistory(),
routes: [...]
})
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth) {
// 鉴权逻辑
if (auth.check()) {
next()
} else {
next('/login')
}
} else {
next()
}
})
可以看到,和Vue2一样,Vue3中依然提供了全局前置守卫的功能,通过beforeEach
方法来定义。
路由独享的守卫
javascriptCopy Codeconst router = createRouter({
history: createWebHistory(),
routes: [
{
path: '/about',
component: About,
beforeEnter: (to, from, next) => {
// 条件判断
if (isLogin) {
next()
} else {
next('/login')
}
}
}
]
})
在Vue3中,路由独享的守卫和全局前置守卫的使用方式略有不同。通过在路由配置中使用beforeEnter
属性来定义。
组件内的守卫
javascriptCopy Codeexport default {
beforeRouteEnter(to, from, next) {
// 组件未创建时调用
next()
},
beforeRouteUpdate(to, from, next) {
// 组件复用时调用
next()
},
beforeRouteLeave(to, from, next) {
// 组件销毁时调用
next()
}
}
在Vue3中,组件内的守卫也有了一些变化。可以通过beforeRouteEnter
、beforeRouteUpdate
和beforeRouteLeave
方法来分别处理组件的创建、复用和销毁阶段的路由变化。
嵌套路由
在Vue3中,嵌套路由的使用方式和Vue2略有不同:
javascriptCopy Codeconst router = createRouter({
history: createWebHistory(),
routes: [
{
path: '/',
component: Home,
children: [
{
path: 'about',
component: About
},
{
path: 'contact',
component: Contact
}
]
}
]
})
可以看到,新的Vue Router不再需要使用router-view
的name
属性来定义命名视图,只需要像上面那样在父路由的children
中配置子路由即可。
动态路由
在Vue3中,动态路由的使用方式和Vue2基本相同:
javascriptCopy Codeconst router = createRouter({
history: createWebHistory(),
routes: [
{
path: '/user/:id',
component: User
}
]
})
可以通过:
符号来定义动态路由,然后在组件内通过$route.params
来获取参数值。
总结
Vue Router在Vue3中有了一些变化,但是基本的使用方式还是和Vue2相似的。除了上面介绍的内容之外,Vue3中还支持了scrollBehavior
配置、提供了动态路由的可选参数、新增了视图切换时的过渡效果等。通过学习本文,相信您已经对Vue3中的Vue Router有了全面的了解。