uniapp如何实现路由守卫、路由拦截,权限引导

因为uniapp路由的实现方式和以往vue开发的router路由时不太一样,故官方这么说:

经过一番网上冲浪发现,有两种方式可以实现,

第一种方式:

 

在上述代码中,我们通过监听beforeRouterEnter事件来实现路由守卫。在回调函数中,你可以根据实际需求进行相应的验证和逻辑操作。如果需要继续导航到目标页面,调用next()方法;如果需要取消导航,可以选择不调用next()方法。

也就是说在你要跳转页面时候,触发这个事件,然后回调里面(next())写navigateTo

第二种是通过uni提供的拦截器(文档)实现:

新建interceptor.js

let needLogin = [
                "/pages/tab/index",
]
            let list = ["navigateTo", "redirectTo", "reLaunch", "switchTab"];
            list.forEach(item => { //用遍历的方式分别为,uni.navigateTo,uni.redirectTo,uni.reLaunch,uni.switchTab这4个路由方法添加拦截器
                console.log(item,'router list item')
                uni.addInterceptor(item, {
                    invoke(e) { // 调用前拦截
                        //获取用户的token
                        console.log(e,'routerjs invoke')
                        const token = localStorage.getItem('token')
                        //获取当前页面路径(即url去掉"?"和"?"后的参数)
                        console.log(token,'router index token')
                        const url = e.url.split('?')[0]
                        console.log(url,'router index url')
 
                        console.log(needLogin.includes(url))
                        //判断要打开的页面是否需要验证登录
                        if (needLogin.includes(url) && token == '') {
                            uni.showToast({
                                title: '该页面需要登录才能访问,请先登录',
                                icon: 'none'
                            })
                            uni.navigateTo({
                                url: "/pages/login/login"
                            })
                            return false
                        }
 
 
                        return true
                    },
                    fail(err) { // 失败回调拦截 
                        console.log(err);
                    },
                })
})

然后在main.js中引入

你可以参考插件市场,拦截器应用示例:图片选择api时无权限,引导用户快捷打开系统设置:拦截器应用示例 — 图片选择 - DCloud 插件市场 

猜你喜欢

转载自blog.csdn.net/m0_57033755/article/details/132871892
今日推荐