网站规划与开发实训室建设,备案添加网站,京东网站建设目标是什么,做素材网站存储因为uniapp路由的实现方式和以往vue开发的router路由时不太一样#xff0c;故官方这么说#xff1a; 经过一番网上冲浪发现#xff0c;有两种方式可以实现#xff0c;
第一种方式#xff1a; 在上述代码中#xff0c;我们通过监听beforeRouterEnter事件来实现路由守卫。…因为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) { // 调用前拦截//获取用户的tokenconsole.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 插件市场