在uniapp中使用路由拦截器实现登录校验和页面跳转 路由守卫

您所在的位置:网站首页 uni路由守卫 在uniapp中使用路由拦截器实现登录校验和页面跳转 路由守卫

在uniapp中使用路由拦截器实现登录校验和页面跳转 路由守卫

2024-04-10 21:45| 来源: 网络整理| 查看: 265

在uniapp中使用路由拦截器实现登录校验和页面跳转 路由守卫

1、添加路由拦截器

在Uni-app中,使用路由拦截器可以在路由跳转前进行一些操作,例如登录校验。首先,我们需要在新建的main.js文件中引用uni-simple-router库,然后使用Vue.use方法将其注册为Vue插件。示例代码如下:

import Vue from 'vue' import App from './App.vue' import router from './router' import uniRouter from 'uni-simple-router' Vue.use(uniRouter, { routes: router }) 2、登录校验

要实现登录校验,我们需要在路由拦截器中判断用户是否登录。如果用户未登录,则跳转到登录页面。我们可以在router.js文件中定义路由的meta字段,用来标识需要进行登录校验的路由。示例代码如下:

const routes = [ { path: '/', name: 'home', component: Home }, { path: '/login', name: 'login', component: Login }, { path: '/profile', name: 'profile', component: Profile, meta: { requireAuth: true } // 需要进行登录校验 } ] 3、编写路由拦截器

在路由拦截器中,我们可以使用beforeEach方法来进行登录校验和页面跳转操作。示例代码如下:

uniRouter.beforeEach((to, from, next) => { if (to.meta.requireAuth) { // 判断是否需要登录校验 const token = uni.getStorageSync('token') // 获取本地存储的token if (token) { next() } else { next('/login') // 跳转到登录页面 } } else { next() } })

在上述代码中,我们使用uni.getStorageSync方法来获取本地存储的token。如果存在token,则说明用户已登录,继续执行后续操作。如果不存在token,则说明用户未登录,跳转到登录页面。

4、页面跳转

在需要进行登录校验的页面组件中,我们可以使用this.$router.push方法来进行页面跳转。示例代码如下:

methods: { goToProfile() { this.$router.push('/profile') } }


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3