Uniapp 验证没登录跳转

逻辑:我随便写一个 没有cookie 我就跳转到登录页,而且任何返回都没用

1.在App.vue 里 写 onload 判断是否存在Cookie 【有效否后面验证】

 

 

 2. 在导入Uniapp 拦截器

// 页面白名单,不受拦截
const whiteList = [
    ''
]

function hasPermission(url) {
    // 在白名单中或有登录判断条件可以直接跳转
    if (whiteList.indexOf(url) !== -1 || uni.getStorageSync("cookie")) {
        return true
    }
    return false
}
uni.addInterceptor('navigateTo', {
    // 页面跳转前进行拦截, invoke根据返回值进行判断是否继续执行跳转
    invoke(e) {
        if (!hasPermission(e.url)) {
            // 清除用户信息
            uni.removeStorageSync("cookie")
            uni.removeStorageSync("userInfo")
            uni.reLaunch({
                url: "/pages/login/login"
            })
            return false
        }
        return true
    },
    success(e) {
        console.log("ok");
    }
})
View Code

3.如果cookie过期也跳转:

if (data.code === 401) {
                    this.$refs.uToast.show({
                        message: "登录过期,请您重新登录",
                        type: "error",
                        duration: 2000,
                        complete() {
                            // 清除用户信息
                            uni.removeStorageSync("cookie")
                            uni.removeStorageSync("userInfo")
                            // 跳转登录页面
                            uni.navigateTo({
                                url: "/pages/login/login"
                            })
                        }
                    })
                }
View Code

这样的话,完全做到了。

posted @ 2022-10-19 11:03  咸瑜  阅读(790)  评论(1编辑  收藏  举报