82 lines
2.8 KiB
JavaScript
82 lines
2.8 KiB
JavaScript
import { createRouter, createWebHistory } from 'vue-router'
|
|
import { useUserStore } from '@/stores/user'
|
|
|
|
const routes = [
|
|
{ path: '/', name: 'index', component: () => import('@/views/index/index.vue') },
|
|
{ path: '/chat', name: 'Chat', component: () => import('@/views/wxPage/ChatEdit.vue'), meta: { requiresAuth: false } },
|
|
{ path: '/balance', name: 'Balance', component: () => import('@/views/wxPage/BalanceEdit.vue'), meta: { requiresAuth: false } },
|
|
{ path: '/works', name: 'Works', component: () => import('@/views/work/works.vue'), meta: { requiresAuth: true } },
|
|
{ path: '/about', name: 'About', component: () => import('@/views/About.vue') },
|
|
{ path: '/profile', name: 'Profile', component: () => import('@/views/Profile.vue'), meta: { requiresAuth: true } },
|
|
{ path: '/article', name: 'Article', component: () => import('@/views/article/list.vue') },
|
|
{ path: '/article-detail', name: 'ArticleDetail', component: () => import('@/views/article/detail.vue') },
|
|
{ path: '/gongzidan', name: 'GongZiDan', component: () => import('@/views/other/gongzidan.vue') },
|
|
]
|
|
|
|
const router = createRouter({
|
|
history: createWebHistory(),
|
|
routes,
|
|
})
|
|
|
|
router.beforeEach(async (to, from, next) => {
|
|
const token = localStorage.getItem('token')
|
|
const userStore = useUserStore()
|
|
|
|
// 如果有 token 但还没验证过,无论是进哪个页面,都静默验证一下以恢复全局状态
|
|
if (token && !userStore.tokenChecked) {
|
|
try {
|
|
await userStore.fetchProfile()
|
|
if (!userStore.tokenValid) {
|
|
localStorage.removeItem('token')
|
|
}
|
|
} catch {
|
|
localStorage.removeItem('token')
|
|
userStore.reset()
|
|
}
|
|
}
|
|
|
|
// 不需要认证的页面,直接放行
|
|
if (!to.meta.requiresAuth) return next()
|
|
|
|
if (!token || !userStore.tokenValid) {
|
|
return next({ path: '/', query: { showLogin: 1 } })
|
|
}
|
|
|
|
next()
|
|
})
|
|
|
|
router.onError((error) => {
|
|
const pattern = /Failed to fetch dynamically imported module|Importing a module script failed/i
|
|
if (pattern.test(error?.message || '')) {
|
|
if (window._chunkErrorHandled) return
|
|
window._chunkErrorHandled = true
|
|
|
|
const forceReload = () => {
|
|
const url = new URL(window.location.href)
|
|
url.searchParams.set('t', Date.now())
|
|
window.location.href = url.href
|
|
}
|
|
|
|
const cleanAndReload = () => {
|
|
if ('serviceWorker' in navigator) {
|
|
navigator.serviceWorker.getRegistrations().then(registrations => {
|
|
for (const registration of registrations) {
|
|
registration.unregister()
|
|
}
|
|
forceReload()
|
|
}).catch(() => { forceReload() })
|
|
} else {
|
|
forceReload()
|
|
}
|
|
}
|
|
|
|
if (window.confirm('系统检测到版本更新,当前页面数据已过期。点击【确定】立即刷新体验最新版本!')) {
|
|
cleanAndReload()
|
|
} else {
|
|
window._chunkErrorHandled = false
|
|
}
|
|
}
|
|
})
|
|
|
|
export default router
|