导航守卫

前言:导航守卫一共被分为3类:全局守卫,单个路由独享守卫,组件内守卫。

导航:表示路由正在发生改变

谨记:参数或查询的改变并不会触发进入/离开的导航守卫,可以使用beforeRouteUpdate来应对这些变化,或者通过观察$route

一、全局守卫

        1.全局前置守卫      

//一般是写在main.js里

router.beforeEach((to, from, next) => {
    //模拟登录检测
    const token = false;
    if(token) {
        //已登录
        next();
    }else{ //未登录
        if(to.path === '/login') next();
        else{next('/login')}
    }


})  //参数本身是一个回调函数  

2.全局后置钩子

router.afterEach((to, from) => {


})

二、路由独享守卫

const routes = [

    {
        path: '/cart',
        component: () => import('@/views/Cart.vue'),
        beforeEnter: (to, from, next)  => {....}

    }


]

三、组件内守卫

        1.beforeRouteEnter

        2.beforeRouterUpdate

        3.beforeRouterLeave

export default {
    beforeRouteEnter(to, from, next) {....}

    beforeRouteUpdate(to, from, next) {
        
    
    }
    
    beforeRouteLeave(to, from, next) {....}

}

### 路由导航守卫的概念 路由导航守卫是一种用于控制页面跳转逻辑的机制,在端框架中广泛应用于权限验证、数据预加载以及页面访问拦截等功能。以下是 Vue.js 和 React 中实现路由导航守卫的具体方法。 --- ### Vue.js 中的路由导航守卫 Vue Router 提供了全局守卫、路由独享守卫和组件内的守卫三种方式来实现导航守卫功能[^1]。 #### 全局守卫 (`beforeEach`) 通过 `router.beforeEach` 方法可以在每次路由切换执行特定逻辑: ```javascript // 定义全局守卫 router.beforeEach((to, from, next) => { if (to.meta.requiresAuth && !isAuthenticated()) { // 如果目标路由需要认证且未登录,则重定向到登录页 next('/login'); } else { next(); // 继续导航 } }); ``` #### 路由独享守卫 (`beforeEnter`) 可以通过在路由定义时设置 `beforeEnter` 来为某个具体路由添加单独的守卫逻辑: ```javascript const routes = [ { path: '/dashboard', component: Dashboard, meta: { requiresAuth: true }, beforeEnter: (to, from, next) => { if (!isAuthenticated()) { next('/login'); // 非授权用户重定向至登录页 } else { next(); } } } ]; ``` #### 组件内守卫 还可以在组件内部定义三个生命周期钩子函数:`beforeRouteEnter`, `beforeRouteUpdate`, 和 `beforeRouteLeave`,分别对应进入组件、更新组件和离开组件时的行为。 ```javascript export default { beforeRouteEnter(to, from, next) { console.log('即将进入该组件'); next(vm => { vm.initData(); // 初始化数据 }); }, beforeRouteLeave(to, from, next) { const confirmLeave = window.confirm('您确定要离开吗?'); if (confirmLeave) { next(); } else { next(false); } } }; ``` --- ### React 中的路由导航守卫 React 并没有像 Vue Router 这样的内置守卫机制,但可以通过自定义高阶组件(HOC)或者条件渲染的方式实现类似的导航守卫效果[^3]。 #### 使用 HOC 实现守卫 创建一个通用的高阶组件来封装守卫逻辑: ```javascript import React from 'react'; import { Redirect } from 'react-router-dom'; function withAuthGuard(Component) { return function AuthenticatedComponent(props) { const isAuthenticated = props.isAuthenticated; if (!isAuthenticated) { return <Redirect to="/login" />; } return <Component {...props} />; }; } export default withAuthGuard; ``` 然后将其包裹在受保护的组件外部使用: ```javascript import React from 'react'; import { Route } from 'react-router-dom'; import ProtectedPage from './ProtectedPage'; import withAuthGuard from './withAuthGuard'; const App = () => ( <Route path="/protected" render={(props) => ( <withAuthGuard isAuthenticated={false}> <ProtectedPage /> </withAuthGuard> )} /> ); export default App; ``` #### 使用条件渲染 另一种简单的方法是在组件内部直接判断用户的登录状态并决定是否允许访问: ```javascript import React from 'react'; import { Redirect } from 'react-router-dom'; class SecurePage extends React.Component { constructor(props) { super(props); this.state = { isLoggedIn: false, // 假设初始状态下未登录 }; } componentDidMount() { fetchUserStatus().then((isLoggedIn) => { this.setState({ isLoggedIn }); }); } render() { if (!this.state.isLoggedIn) { return <Redirect to="/login" />; } return <div>这是安全页面</div>; } } ``` --- ### 总结 无论是 Vue.js 还是 React,都可以灵活地实现路由导航守卫功能。Vue Router 提供了更加直观和便捷的支持,而 React 则依赖于开发者自行设计解决方案。两种方式各有优劣,需根据具体的业务需求和技术栈特点选择合适的方案[^1][^3]。 ---
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值