微信小程序 全局路由守卫 vue3 ts

81 阅读1分钟

//微信小程序 全局路由守卫 vue3 ts

 export const globalRouteGuard = () =>{
    const originalMethods: Record<UniNavMethod, Function> = {} as any
    const navMethods: UniNavMethod[] = ['navigateTo', 'redirectTo', 'reLaunch', 'switchTab']
    // 定义登录页路径和白名单路径
    const LOGIN_PAGE_PATH = '/pages/login/login'
    const WHITE_LIST = [
        '/pages/distributor/distributor',
        '/pages/index/message/ball_record',
        '/pages/index/message/online_queuing',
        '/pages/index/message/lineUp_begin',
        '/pages/event_center/participate'
    ] // 添加你的白名单路径

    navMethods.forEach((method) => {
        const uniTyped = uni as UniMethod
        const originalMethod = uniTyped[method]

        if (typeof originalMethod === 'function') {
            originalMethods[method] = originalMethod

            uniTyped[method] = function (options: { url?: string }) {
                const pages = getCurrentPages()
                const currentPage = pages[pages.length - 1]
                const currentRoute = currentPage?.route || ''
                const purePath = options.url?.split('?')[0]
                console.log(`即将从 ${currentRoute} 跳转至: ${purePath}`)

                const token = uni.getStorageSync('token')

                // 判断目标路径是否为白名单或登录页
                const isTargetInWhiteList = purePath && !WHITE_LIST.includes(purePath)
                console.log('isTargetInWhiteList', isTargetInWhiteList)


                // 用户未登录
                if (!token) {
                    // 如果目标不在白名单中,并且当前不是登录页,则强制跳转到登录页
                    if (!isTargetInWhiteList && `/${currentRoute}` !== LOGIN_PAGE_PATH) {
                        uni.showToast({ title: '请先登录', icon: 'none' })
                        return originalMethods.navigateTo.call(this, { url: LOGIN_PAGE_PATH })
                    }
                }

                // 白名单页面 或 已登录用户,正常执行原始方法
                return originalMethods[method].call(this, options)
            }
        }
    })

}

//直接导出在mian.ts文件应用就可以了

4aa1e049ea4b4cd180bcd40038e146b3.png