js es6 import动态引用变量+解决无法import xxx.vue问题

Vue的component通过eval配合js模板语法动态添加路由

const routesMap = ["Home", "QQ", "WeChat", "TikTok", "Personal", "Authorization",
	"GroupSend", "Assignment", "Script", "ApplyUpdates", "Equipment", "DeviceGroup"
]
let Path, routesChildren = []
routesMap.forEach(Item => {
	routesChildren.push({
		path: '/' + Item,
		component: eval(`() => import("./views/childs/${Item}.js")`)
	})
})

Vue全局使用csdn引入,解决无法import xxx.vue问题

创建js文件,引用如下内容模板

export default {
	template: `
................
`
, data() { return {} }, methods: {}, mounted() {} };

示例

Module.js

export default {
	template: `
`
, data() { return { demo:"hello world!" } }, methods: {}, mounted() {} };

router.js

const routesMap = ["Module"]
let Path, routesChildren = []
routesMap.forEach(Item => {
	routesChildren.push({
		path: '/' + Item,
		component: eval(`() => import("./views/childs/${Item}.js")`)
	})
})
const routes = [{
		path: '/Index',
		component: () => import("./views/Index.js"),
		children: routesChildren
	},
	{
		path: '/Entrance',
		component: () => import("./views/Entrance.js")
	}
]
/**以上仅将children使用动态创建**/
const router = new VueRouter({
	routes
})
/**解决push报错**/
const VueRouterPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(to) {
	return VueRouterPush.call(this, to).catch(err => err)
}
export default router;

main.js

import router from "./router.js"
let Main = {
	router,
	methods: {},
	created() {
	this.$router.push("../Index")
	}
};
let Ctor = Vue.extend(Main);
new Ctor().$mount('#app');

index.html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>CLOUD_CONTROL</title>
		<link rel="stylesheet" type="text/css" href="static/basic.css" />
		<link rel="stylesheet" type="text/css" href="static/element.min.css" />
		<script src="static/vue.js" type="text/javascript" charset="utf-8"></script>
		<script src="static/vue-router.js" type="text/javascript" charset="utf-8"></script>
		<script src="static/element.min.js" type="text/javascript" charset="utf-8"></script>
	</head>
	<body>
		<div id="app" v-cloak>
			<router-view></router-view>
		</div>
	</body>
	<link rel="stylesheet" type="text/css" href="css/entrance_mc.css" />
	<link rel="stylesheet" type="text/css" href="css/home_mc.css" />
	<script type="module" src="main.js"></script>
</html>

注意:以上直接拷贝运行结果可能有出入,只是整体的流程思路

你可能感兴趣的:(vue,element,es6,javascript,vue.js,es6)