Vue 3 使用Vue Router来管理路由,路由守卫和拦截用于在导航到不同页面之前执行一些操作,例如身份验证、权限检查、数据加载等。以下是Vue 3中使用路由守卫和拦截的基本示例:
首先,确保你已经安装了Vue Router。如果还没有安装,你可以使用以下命令安装:
npm install vue-router
然后,在你的Vue项目中创建一个路由实例并配置路由规则。以下是一个示例:
// main.js
import { createApp } from 'vue'
import App from './App.vue'
import { createRouter, createWebHistory } from 'vue-router'const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/', component: Home },
{ path: '/about', component: About },
// 其他路由规则
]
})const app = createApp(App)
app.use(router)
app.mount('#app')
接下来,你可以使用路由守卫来拦截导航。Vue 3 提供了三种类型的路由守卫:
1、全局前置守卫:在路由导航开始之前触发,适用于全局设置。
router.beforeEach((to, from, next) => {
// 在导航前执行操作,例如身份验证检查
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login'); // 重定向到登录页
} else {
next(); // 继续导航
}
})
2、路由独享守卫:在特定路由上设置的守卫。
const routes = [
{
path: '/dashboard',
component: Dashboard,
beforeEnter: (to, from, next) => {
// 在导航到特定路由前执行操作
if (!hasPermission) {
next('/access-denied'); // 重定向到权限拒绝页
} else {
next(); // 继续导航
}
}
}
]
3、组件内的守卫:在组件内部定义的守卫。
export default {
beforeRouteEnter(to, from, next) {
// 在组件路由进入前执行操作
if (!isAuthenticated) {
next('/login');
} else {
next();
}
},
beforeRouteLeave(to, from, next) {
// 在组件路由离开前执行操作
if (unsavedChanges) {
if (confirm('您有未保存的更改,确定离开吗?')) {
next();
} else {
next(false); // 取消导航
}
} else {
next();
}
}
}
上述示例中,你可以在路由守卫中执行所需的操作,然后使用next
函数来控制导航的继续或取消。
请根据你的项目需求,选择适当的守卫类型并在路由配置中设置它们。这有助于实现身份验证、权限控制和其他与导航相关的功能。