import { isEmpty } from '@/utils' import store from '@/store' const Article = () => import('@/components/Article') const Login = () => import('@/components/Login') const Register = () => import('@/components/Register') const Onlinewebsocket = () => import('@/components/Onlinewebsocket') const Home = () => import('@/components/Home') const Bilicom = () => import('@/components/Bilicom') const Mavoneditor = () => import('@/components/Mavoneditor') const GrilShow = () => import('@/components/GrilShow') const Csslearn = () => import('@/components/Csslearn') const defaultRoutes = [ { path: '/', name: 'Article', component: Article, hidden: true }, { path: '/login', name: 'Login', component: Login, hidden: false }, { path: '/register', name: 'Register', component: Register, hidden: false }, { path: '/home', name: 'Home', component: Home, hidden: true }, { path: '/onlinewebsocket', name: 'Onlinewebsocket', component: Onlinewebsocket, hidden: true }, { path: '/bilicom', name: 'Bilicom', component: Bilicom, hidden: true }, { path: '/mavoneditor', name: 'Mavoneditor', component: Mavoneditor, hidden: true }, { path: '/gril', name: 'grilshow', component: GrilShow, hidden: true }, { path: '/css', name: 'css', component: Csslearn, hidden: true } ] const useRouter = (Vue, VueRouter) => { let routes = [ ...defaultRoutes ] const originalPush = VueRouter.prototype.push VueRouter.prototype.push = function push (location) { return originalPush.call(this, location).catch((err) => err) } // 路由 const router = new VueRouter({ routes }) // const whiteList = ['/login', '/register'] router.beforeEach(async (to, from, next) => { let yma16siteUserInfo = localStorage.getItem('yma16siteUserInfo') ? JSON.parse(localStorage.getItem('yma16siteUserInfo')) : {} let name = yma16siteUserInfo.username let pwd = yma16siteUserInfo.password console.log('to', to) let hasToken = { name: name, password: pwd } console.log('localStorage', hasToken) if (hasToken.name && hasToken.password) { if (!isEmpty(store.state.user.userInfo)) { try { // 空的 modules下的user console.log('路由的登录认证') // 用户自主登录 await store.dispatch('user/loginUserInfo', hasToken) next() } catch (e) { console.error(e, 'e') if (to.name === 'Login' || to.path === '/login' || to.name === 'register' || to.path === '/Register') { // 避免同名路由无限循环 console.log('next') next() } else { console.log('login router') return next({ name: 'Login' }) // 去登录 } } } else { console.log('next') next() } } else if (to.name === 'Login' || to.path === '/login' || to.name === 'Register' || to.path === '/register') { console.log('next login register') // 避免同名路由无限循环 next() } else { console.log('login router') return next({ name: 'Login' }) // 去登录 } return false }) Vue.use(VueRouter) return router } export default useRouter