uniapp中H5的登录拦截

uniapp中H5的登录拦截

uniapp不能很简便的直接做登录拦截,也试过在App.vue的onShow去写,但效果不是特别好,最后用uni-simple-router解决的(http://www.hhyang.cn/src/router/start/introduction.html)

解决方案

一.下载包
在uniapp中的终端标签卡(推荐,虽然可以在插件市场中下载或导入)

npm install uni-simple-router

二.初始化
1.项目根目录创建router文件夹(文件夹内创建如下结构用于放置路由相关文件:)

router
    |--modules
    |   |--index.js
    |   |--home.js
    |--index.js

2.router里面有个modules文件夹,这是专门放置路由表模块的。 modules内的index.js如下编写

// router/modules/index.js
const files = require.context('.', false, /\.js$/)
const modules = []

files.keys().forEach(key => {
  if (key === './index.js') return
  const item = files(key).default
  modules.push(...item)
})

export default modules

3.modules内的home.js用于存放首页及其相关的路由(记得要写全,不然页面会没有显示)

// router/modules/home.js
const home = [
	{
        //注意:path必须跟pages.json中的地址对应,最前面别忘了加'/'哦
      path: '/pages/home/index',
      aliasPath:'/',  //对于h5端你必须在首页加上aliasPath并设置为/
      name: 'index',
      requiresAuth: false, //可选配置 (是否权限路由)(我用来做登录拦截,true时没有登录便会跳转到登录页面)
        meta: {
	        title: '首页',
	    },
    },
    {
	    path: '/pages/home/list',
        name: 'list',
        requiresAuth: false, //可选配置 (是否权限路由)
        meta: {
	        title: '列表',
	    },
	},{
		path: "/pages/shopCar/shopCar",
		name: 'shopCar',
		requiresAuth: true,
		meta: {
			title: "购物车"
		}
	},
]
export default home

4.router下的index.js,配置如下

// router/index.js

import modules from './modules'
import Vue from 'vue'
//这里仅示范npm安装方式的引入,其它方式引入请看最上面【安装】部分
import Router from 'uni-simple-router'

Vue.use(Router)
//初始化
const router = new Router({
    routes: [...modules]//路由表
});

//全局路由前置守卫
router.beforeEach((to, from, next) => {
//这里写登录拦截(我没有写全,如果获取到了token就不用跳转到登录页,就直接next())
  if(to.requiresAuth) {
		next({
			path: '/pages/login/login',
			NAVTYPE: 'push'
		});
	} else {
		next();
	}
})
// 全局路由后置守卫
router.afterEach((to, from) => {
})
export default router;

5.根目录下找到main.js,引入router

// main.js
import Vue from 'vue'
import App from './App'
import router from './router'
import { RouterMount } from 'uni-simple-router'

App.mpType = 'app'

const app = new Vue({
	...App
})
//v1.3.5起 H5端 你应该去除原有的app.$mount();使用路由自带的渲染方式
// #ifdef H5
	RouterMount(app,'#app');
// #endif

// #ifndef H5
	app.$mount(); //为了兼容小程序及app端必须这样写才有效果
// #endif

6.在登录页面登录成功进行跳转

uni.showToast({
	title: '登录成功',
	duration: 2000,
	icon: 'none'
});
setTimeout(function() {
	// 跳转回原页面
	history.back()
}, 2000);
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值