自学内容网 自学内容网

vue3路由导航守卫配置

首先声明:我是结合vuex写的例子。

效果介绍:比如我登录之后他会根据我们登陆完毕的code是否为1,如果是1的话,则进入首页,这个时候无法访问登录页面,除非退出,在code为0的时候无法进入首页。也无法通过修改url进入首页。

代码分析:

我将路由页面全部代码放置如下

import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import store from '../store'; //路径:用来重定向页面


// 定义路由
const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView
  },
  {
    path: '/about',
    name: 'about',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: function () {
      return import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
    },
    meta: { requiresAuth: true }, // 表示访问首页需要认证
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})




router.beforeEach((to, from, next) => {
  const userInfo = store.getters['login/getUserInfo']; // 获取用户信息
  const isAuthenticated = userInfo && userInfo.code === 1; // 假设 code 为 1 表示已登录
  console.log(userInfo.code, '可以打印到我吗?');
  if (to.matched.some(record => record.meta.requiresAuth) && !isAuthenticated) {
    // 如果目标路由需要认证但用户未登录,则重定向到登录页面
    next({ path: '/' });
   
  } else if (to.path === '/' && isAuthenticated) {
    // 如果用户已登录但访问登录页面,则重定向到首页
    next({ path: '/about' });
  } else {
    // 其他情况,允许正常导航
    next();
  }
});



export default router

在这里做一点解释

这个表示访问首页需要认证

meta: { requiresAuth: true }, // 表示访问首页需要认证

这段

就是获取到用户信息,可进行判断code如果为1表示已登录,如果是1表示已经登录如果不是那么表示从新回到登陆页面。


router.beforeEach((to, from, next) => {
  const userInfo = store.getters['login/getUserInfo']; // 获取用户信息
  const isAuthenticated = userInfo && userInfo.code === 1; // 假设 code 为 1 表示已登录
  console.log(userInfo.code, '可以打印到我吗?');
  if (to.matched.some(record => record.meta.requiresAuth) && !isAuthenticated) {
    // 如果目标路由需要认证但用户未登录,则重定向到登录页面
    next({ path: '/' });
   
  } else if (to.path === '/' && isAuthenticated) {
    // 如果用户已登录但访问登录页面,则重定向到首页
    next({ path: '/about' });
  } else {
    // 其他情况,允许正常导航
    next();
  }
});

感谢观看


原文地址:https://blog.csdn.net/A12536365214/article/details/136328809

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!