hookehuyr

配置动态路由功能

const routes = [{
path: '/image',
redirect: '',
name: 'html转图片',
component: 'html2canvas',
keepAlive: '',
meta: {
title: 'html转图片',
name: ''
},
children: []
}]
export default routes
import { createRouter, createWebHashHistory } from 'vue-router';
import routes from './route.js';
import { generateRoute } from './utils/generateRoute'
// TODO: 微信分享测试
import share from '@/utils/share'
......@@ -12,11 +13,16 @@ const router = createRouter({
routes
});
router.beforeEach((to, from, next) => {
next()
// TAG: 动态生成路由
router.beforeEach((to) => { // next 不能用了,被return替代了
if (!router.hasRoute(to.name)) { // 如果不存在
router.addRoute(generateRoute(to)) // 新增路由
// 触发重定向
return to.fullPath
}
})
router.afterEach((to, from, next) => {
router.afterEach(() => {
// console.warn(to);
// console.warn(wx);
// share(to)
......
/**
* 生成动态路由
*/
import _ from 'lodash'
import routes from "../mock/routes"
// 根据后台返回的路径,生成页面的组件模版
function loadView(component) {
return () => import(`../views/${component}.vue`)
}
const formatRoutesArr = []
routes.forEach(route => {
const router = {}
const {
path,
redirect,
name,
component,
keepAlive,
meta,
children
} = route
router.component = loadView(component)
if (redirect !== null) {
router.redirect = redirect
}
if (keepAlive !== null) {
router.keepAlive = keepAlive
}
if (children && children instanceof Array && children.length > 0) {
router.children = formatRoutes(children)
}
if (name !== null) {
router.name = name
}
if (meta !== null) {
router.meta = meta
}
router.path = path
formatRoutesArr.push(router)
})
export const generateRoute = (to) => {
let router = ''
_.each(formatRoutesArr, item => {
if (item.path === to.path) {
router = item
}
})
return _.assign(to, router)
}
......@@ -92,8 +92,6 @@ import { useRoute, useRouter } from 'vue-router'
import axios from '@/utils/axios';
import { Toast } from 'vant';
import IMAGE from '@/views/html2canvas.vue'
const $route = useRoute();
const $router = useRouter();
......@@ -131,28 +129,6 @@ axios.get('/srv/?a=kg_info')
.catch(err => {
console.error(err);
});
// 测试动态路由
/**
* , {
path: '/image',
name: 'html转图片',
component: () => import('./views/html2canvas.vue'),
meta: {
title: ''
}
}
*/
// $router.addRoute({ path: '/image', name: 'html转图片', meta: { title: 'html转图片' }, component: IMAGE})
onMounted(() => {
// setTimeout(() => {
// $router.push({
// path: '/image'
// })
// }, 3000);
})
</script>
<script>
......