npm install tarojs-router
简单实现:
github: https://github.com/lblblong/tarojs-router
创建router配置目录src/router
src/router/middleware/author-check.ts
import storage from '@/utils/storage' import Taro from '@tarojs/taro' import { IMiddlware } from "tarojs-router" import { toLogin } from '../router' export const AuthCheck: IMiddlware<{ mustLogin: boolean }> = async (ctx, next) => { if (ctx.route.ext?.mustLogin) { const token = storage.getItem('token') if (!token) { const { confirm } = await Taro.showModal({ title: '提示', content: '请先登录' }) if (confirm) { toLogin() } throw Error('该页面必须要登陆:' + ctx.route.url) } } await next() }
src/router/index.ts
import { Router } from 'tarojs-router' import { AuthCheck } from './middleware/author-check' export * from './router' Router.config({ middlewares: [AuthCheck] })
src/router/router.ts
import { Router, NavigateType } from 'tarojs-router' import { routes } from './routes' export const toLogin = (params: any = {}, type: string = '') => { let url: string = '' if (IS_H5) { url = `/login/phone/index` } else { url = `/login/index` } if (type) { Router.navigate( { url }, { params, type: NavigateType.navigateTo } ) } else { Router.navigate( { url }, { type: NavigateType.redirectTo } ) } } export const navigateHouseModule = (module: string, params: any = {}, data: any = {}) => { return Router.navigate(routes[module], { params, data }) }
src/router/routes.ts
export const routes = { index: { url: '/pages/index/index' }, me: { url: '/pages/me/index', ext: { mustLogin: true } },
commentForm: {
url: '/house/new/commentForm/index',
beforeRouteEnter: [HasLoginBack],
ext: {
checkLogin: true,
type: 'navigateTo'
}
}
}
src/middleware/auth-check.ts -> hasLoginback:
import storage from '@/utils/storage' import { toUrlParam } from '@/utils/urlHandler' import { IMiddlware } from "tarojs-router" import { toLogin } from '../router' interface ILoginBack { checkLogin: boolean type: string } export const HasLoginBack: IMiddlware<ILoginBack> = async (ctx, next) => { if (ctx.route.ext?.checkLogin) { const token = storage.getItem('token') if (!token) { const isTab = ctx.params.isTab || '' const backUrl = `${ctx.route.url}${toUrlParam(ctx.params)}` toLogin({ backUrl: encodeURIComponent(backUrl), isTab }, ctx.route.ext?.type)
throw Error('该页面必须要登陆:' + ctx.route.url) // 不加h5会继续跳转
} } await next() }