Skip to content

Commit

Permalink
feat(router): Add dynamic routing
Browse files Browse the repository at this point in the history
  • Loading branch information
kailong502431556 committed Jan 11, 2022
1 parent 95a2bd8 commit b218ccc
Show file tree
Hide file tree
Showing 15 changed files with 482 additions and 327 deletions.
5 changes: 4 additions & 1 deletion src/api/login/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,8 @@ import type { UserLoginType } from './types'
const { request } = useAxios()

export const loginApi = (data: UserLoginType) => {
return request({ url: '/user/login', method: 'post', data })
return request({ url: '/user/login', method: 'post', data } as AxiosConfig<
Recordable,
UserLoginType
>)
}
10 changes: 2 additions & 8 deletions src/hooks/web/useAxios.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,8 @@ import { config } from '@/config/axios/config'
const { default_headers } = config

export function useAxios() {
function request({
url,
method,
params,
data,
headersType,
responseType
}: AxiosConfig): AxiosPromise {
function request(option: AxiosConfig): AxiosPromise {
const { url, method, params, data, headersType, responseType } = option
return service({
url: url,
method,
Expand Down
31 changes: 16 additions & 15 deletions src/hooks/web/useNProgress.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { watch, ref, nextTick, unref } from 'vue'
import { nextTick, unref } from 'vue'
import type { NProgressOptions } from 'nprogress'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
Expand All @@ -7,26 +7,27 @@ import { useCssVar } from '@vueuse/core'
const primaryColor = useCssVar('--el-color-primary', document.documentElement)

export function useNProgress() {
const isLoading = ref(false)
NProgress.configure({ showSpinner: false } as NProgressOptions)
initColor()

watch(
() => isLoading.value,
async (loading: boolean) => {
loading ? NProgress.start() : NProgress.done()
await nextTick()
const bar = document.getElementById('nprogress')?.getElementsByClassName('bar')[0] as ElRef
if (bar) {
bar.style.background = unref(primaryColor.value)
}
async function initColor() {
await nextTick()
const bar = document.getElementById('nprogress')?.getElementsByClassName('bar')[0] as ElRef
if (bar) {
bar.style.background = unref(primaryColor.value)
}
)
}

function start() {
NProgress.start()
}

function toggle() {
isLoading.value = !isLoading.value
function done() {
NProgress.done()
}

return {
toggle
start,
done
}
}
19 changes: 13 additions & 6 deletions src/layout/Layout.vue
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
<script setup lang="ts"></script>
<script setup lang="ts">
// import { computed } from 'vue'
// const getCaches = computed((): string[] => {
// return []
// })
</script>

<template>
<section>
<router-view v-slot="{ Component, route }">
<component :is="Component" :key="route.fullPath" />
</router-view>
</section>
<RouterView>
<template #default="{ Component, route }">
<KeepAlive>
<Component :is="Component" :key="route.fullPath" />
</KeepAlive>
</template>
</RouterView>
</template>
11 changes: 9 additions & 2 deletions src/locales/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,19 @@ export default {
login: 'Sign in',
otherLogin: 'Sign in with',
remember: 'Remember me',
forgetPassword: 'Forget password'
forgetPassword: 'Forget password',
usernamePlaceholder: 'username is admin or test',
passwordPlaceholder: 'password is admin or test'
},
router: {
login: 'Login',
level: 'Multi level menu',
menu: 'Menu'
menu: 'Menu',
menu1: 'Menu1',
menu11: 'Menu1-1',
menu111: 'Menu1-1-1',
menu12: 'Menu1-2',
menu2: 'Menu2'
},
mock: {
loginErr: 'Wrong account or password'
Expand Down
11 changes: 9 additions & 2 deletions src/locales/zh-CN.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,19 @@ export default {
login: '登录',
otherLogin: '其他登录方式',
remember: '记住我',
forgetPassword: '忘记密码'
forgetPassword: '忘记密码',
usernamePlaceholder: '用户名为 admin 或者 test ',
passwordPlaceholder: '密码为 admin 或者 test '
},
router: {
login: '登录',
level: '多级菜单',
menu: '菜单'
menu: '菜单',
menu1: '菜单1',
menu11: '菜单1-1',
menu111: '菜单1-1-1',
menu12: '菜单1-2',
menu2: '菜单2'
},
mock: {
loginErr: '账号或密码错误'
Expand Down
44 changes: 22 additions & 22 deletions src/permission.ts
Original file line number Diff line number Diff line change
@@ -1,40 +1,40 @@
import router from './router'
import { useAppStoreWithOut } from '@/store/modules/app'
import { useCache } from '@/hooks/web/useCache'
// import type { RouteRecordRaw } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { useTitle } from '@/hooks/web/useTitle'
import { useNProgress } from '@/hooks/web/useNProgress'
import { usePermissionStoreWithOut } from '@/store/modules/permission'

const permissionStore = usePermissionStoreWithOut()

const appStore = useAppStoreWithOut()

const { wsCache } = useCache()

const { toggle } = useNProgress()
const { start, done } = useNProgress()

const whiteList = ['/login'] // 不重定向白名单

router.beforeEach((to, from, next) => {
console.log(from)
toggle()
router.beforeEach(async (to, from, next) => {
start()
if (wsCache.get(appStore.getUserInfo)) {
if (to.path === '/login') {
next({ path: '/' })
} else {
// if (permissionStore.getIsAddRouters) {
// next()
// return
// }
// permissionStore.generateRoutes().then(() => {
// permissionStore.addRouters.forEach(async (route) => {
// await router.addRoute(route as RouteRecordRaw) // 动态添加可访问路由表
// })
// const redirectPath = from.query.redirect || to.path
// const redirect = decodeURIComponent(redirectPath as string)
// const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect }
// permissionStore.setIsAddRouters(true)
// next(nextData)
// })
next()
if (permissionStore.getIsAddRouters) {
next()
return
}
await permissionStore.generateRoutes()
permissionStore.getAddRouters.forEach((route) => {
router.addRoute(route as unknown as RouteRecordRaw) // 动态添加可访问路由表
})
const redirectPath = from.query.redirect || to.path
const redirect = decodeURIComponent(redirectPath as string)
const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect }
permissionStore.setIsAddRouters(true)
next(nextData)
}
} else {
if (whiteList.indexOf(to.path) !== -1) {
Expand All @@ -45,7 +45,7 @@ router.beforeEach((to, from, next) => {
}
})

router.afterEach(async (to) => {
router.afterEach((to) => {
useTitle(to?.meta?.title as string)
toggle() // 结束Progress
done() // 结束Progress
})
27 changes: 0 additions & 27 deletions src/router/helper.ts

This file was deleted.

125 changes: 63 additions & 62 deletions src/router/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { createRouter, createWebHashHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import type { App } from 'vue'
// import { getParentLayout } from './helper'
import { getParentLayout } from '@/utils/routerHelper'
import { useI18n } from '@/hooks/web/useI18n'

const { t } = useI18n()

/* Layout */
Expand All @@ -15,7 +16,7 @@ export const constantRouterMap: AppRouteRecordRaw[] = [
name: 'Redirect',
children: [
{
path: '/redirect/:path*',
path: '/redirect/:path(.*)',
name: 'Redirect',
component: () => import('@/views/Redirect/Redirect.vue'),
meta: {}
Expand All @@ -37,66 +38,66 @@ export const constantRouterMap: AppRouteRecordRaw[] = [
}
]

// export const asyncRouterMap: AppRouteRecordRaw[] = [
// {
// path: '/level',
// component: Layout,
// redirect: '/level/menu1/menu1-1/menu1-1-1',
// name: 'Level',
// meta: {
// title: t('router.level')
// },
// children: [
// {
// path: 'menu1',
// name: 'Menu1',
// component: getParentLayout('Menu1'),
// redirect: '/level/menu1/menu1-1/menu1-1-1',
// meta: {
// title: `${t('router.menu')}1`
// },
// children: [
// {
// path: 'menu1-1',
// name: 'Menu11',
// component: getParentLayout('Menu11Demo'),
// redirect: '/level/menu1/menu1-1/menu1-1-1',
// meta: {
// title: `${t('router.menu')}1-1`,
// alwaysShow: true
// },
// children: [
// {
// path: 'menu1-1-1',
// name: 'Menu111',
// component: () => import('@/views/Level/Menu111.vue'),
// meta: {
// title: `${t('router.menu')}1-1-1`
// }
// }
// ]
// },
// {
// path: 'menu1-2',
// name: 'Menu12',
// component: () => import('@/views/Level/Menu12.vue'),
// meta: {
// title: `${t('router.menu')}1-2`
// }
// }
// ]
// },
// {
// path: 'menu2',
// name: 'Menu2Demo',
// component: () => import('@/views/Level/Menu2.vue'),
// meta: {
// title: `${t('router.menu')}2`
// }
// }
// ]
// }
// ]
export const asyncRouterMap: AppRouteRecordRaw[] = [
{
path: '/level',
component: Layout,
redirect: '/level/menu1/menu1-1/menu1-1-1',
name: 'Level',
meta: {
title: t('router.level')
},
children: [
{
path: 'menu1',
name: 'Menu1',
component: getParentLayout(),
redirect: '/level/menu1/menu1-1/menu1-1-1',
meta: {
title: t('router.menu1')
},
children: [
{
path: 'menu1-1',
name: 'Menu11',
component: getParentLayout(),
redirect: '/level/menu1/menu1-1/menu1-1-1',
meta: {
title: t('router.menu11'),
alwaysShow: true
},
children: [
{
path: 'menu1-1-1',
name: 'Menu111',
component: () => import('@/views/Level/Menu111.vue'),
meta: {
title: t('router.menu111')
}
}
]
},
{
path: 'menu1-2',
name: 'Menu12',
component: () => import('@/views/Level/Menu12.vue'),
meta: {
title: t('router.menu12')
}
}
]
},
{
path: 'menu2',
name: 'Menu2Demo',
component: () => import('@/views/Level/Menu2.vue'),
meta: {
title: t('router.menu2')
}
}
]
}
]

const router = createRouter({
history: createWebHashHistory(),
Expand Down
Loading

0 comments on commit b218ccc

Please sign in to comment.