「这是我参与2022首次更文挑战的第8天,活动详情查看:2022首次更文挑战」
设计两个函数,一个是加载组件的,一个是页面刷新后根据 url路径 加载组件的函数。
// 加载路由指定的组件
const getComponent = (key) => {
const route = routes[key]
if (route) {
// 设置标题
document.title = route.title
// 设置url地址
window.history.pushState(null, null, baseUrl + route.path)
// 返回组件
return defineAsyncComponent(route.component)
} else {
return home
}
}
// 刷新时依据url加载组件
const refresh = (cb) => {
const path = window.location.pathname
if (path === '/' || path === baseUrl) {
// 首页
} else {
const tmp = path.replace(baseUrl, '')
// 加载组件
for (const key in routes) {
const route = routes[key]
if (route.path === tmp) {
if (typeof cb === 'function'){
cb(key)
}
break
}
}
}
}
// 导出配置和函数
export {
group,
routes,
getComponent,
refresh
}
-
设置标题和 URL 地址
点击菜单,加载组件,顺便设置一下浏览器的标题和 URL 的路径。
虽然现在浏览器都是标签的形式,没有太大的空间显示标题,不过设置一下标题也不麻烦。
然后用 window.history.pushState 设置一下浏览器的 URL 路径,这样设置不会导致浏览器向服务器请求页面。 -
刷新自动加载组件
刷新页面后如果不做设置的话,是不会依据 URL 加载对应的组件的,所以还需要我们写个函数处理一下。
首先获取 URL 的路径(pathName),然后到路由设置里面查找对应的组件,然后加载即可。
这里做了一个回调函数,可以更方便一些。
使用动态组件(component)加载图标 ,其他的按照 el-menu 的要求进行设置即可
设计权限的时候,需要标注可以访问哪些菜单,也就是组件,然后设置好对应的菜单(路由)的 key 即可。绑定的地方换成过滤后的数组即可。
如果想做成 tab 标签页的形式要怎么做呢?
其实也很简单,我们只需要增加一个 数组 (Set,tabs) 用于存放点击过的菜单的key,然后依据 tabs 绑定 el-tabs 即可
<el-tabs
v-model="currentRoute.key"
type="card"
>
<el-tab-pane
v-for="key in tabs"
:key="key"
:label="routes[key].title"
:name="key"
>
<template #label>
<span>{{routes[key].title}}
<circle-close-filled
style="width: 1.0em; height: 1.0em; margin-top: 8px;"
@click.stop="removeTab(key)" />
</span>
</template>
<component :is="routerControl[key]">
</component>
</el-tab-pane>
</el-tabs>