これは非常に言葉にならない。。。。何度か試したところ、最初のエントリページはブロックされていないことがわかり、認証状況を判断するためのユニアプリを作成するつもりですが、これは初回以降のみトリガーされます(WeChat公式アカウントのH5ページを共有しているため、最初にインターセプトを入力する必要があります。最初のログインインターセプトの要件がない場合は、一番下のコードを参照してください)。。2つのケースがあります
共有が必要なページのonloadでトークンの有無を判定
onLoad(e) {
console.log(333)
console.log(e, 'eeeeeeejinxing')
console.log(e.myid, 'e.myid')
console.log(e.activityId, 'e.activityId')
console.log(e.id)
if (e.myid || e.activityId) {
this.shareId = e.myid;
let token = localStorage.getItem('token');
console.log("1111");
console.log(token);
if (token) {
console.log('token')
this.user(e.activityId)
} else {
console.log('notoken')
this.getWechatCode(e.activityId);
}
console.log('1.111')
// this.being(e.activityId)
return
} else {
console.log('2222')
// this.uid = JSON.parse(localStorage.getItem('userInfo')).id
// console.log(this.uid, 'uididddd')
this.being(e.id)
this.activityId = e.id;
}
// this.share()
//uid分享出去的人的id id是活动id
},
app.vue の onLaunch には次のコードがあります。ページに直接入ってトークンの有無を判断し、強制的にホームページにジャンプします(WeChatの認証はログインページなしでホームページ上で取得します)ジャンプはタブバーページかどうかを区別する必要があります
let token = uni.getStorageSync('token')
if (token) {
} else {
uni.reLaunch({
url: "/pages/tab/index",
success: () => {
}
})
}
実際には、さらにいくつかあります。たとえば、vuex、またはログイン コードのフラグメントをカプセル化して main.js に混合します。ただし、これらのいずれも試していません。実際、これら 2 つはルーティング インターセプトほど便利ではありません。。。しかし、この uniapp インターセプターは非常に悪趣味で、vue の router.beforeEach を使用できません。
==================================
実際、最初のログインインターセプトの要件がない場合。App.vue のonLaunchに記述できますが、
(他の人のコード侵害を利用して削除の連絡をしたこともあります)
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);
},
})
})
新しい router/index.js ファイルを作成して書き込むこともできます。main.jsで導入されました