现在的vue应用多半跟webpack一起使用,但是每次发布都需要重新打包,没法通过数据库配置直接生成页面。
常用的远程调用模块
1、seajs
2、ocLazyLoad
3、vue异步组件
因为我们要用vue执行远程调用模块,所有接下来详细介绍vue异步组件的模式
vue异步组件
- 添加vue-router模块的依赖
- 在router配置中,添加获取用户所拥有的菜单,将菜单列表转换成异步组件,动态添加到路由中
router.beforeEach((to, from, next) => {
if (false) {
} else {
if (!store.getters.hasAddRoude) {
store.dispatch('GetUserPowerInfo').then(powerData => {
//菜单加载
//权限
var addRouters = [];
for(let [index, element] of powerData.entries()) {
var item = {
path: element.path, component: function(resolve, reject) {
getDisplayView(element.component).then(res => {
resolve(splitCode(res))
})
}
}
addRouters.push(item);
}
router.addRoutes(addRouters) // 动态添加可访问路由表
next({...to, replace: true })
})
}else {
next() // token已经拿到了
}
}
})
vuex中的user模块的action
// 获取用户权限信息
GetUserPowerInfo({ commit, state }) {
commit('setHadAddRouder', true);
return new Promise((resolve, reject) => {
getMenuConfig().then(res => {
resolve(res)
}).catch(err => {
reject(err)
})
})
},
menu config
[
{
"title": "测试", "name": "aaa", "path": "/aaa", "component": "display.vue"
}
]
display.vue
<!-- display.vue -->
<template>
<div class="bbb">1111</div>
</template>
<script>
export default {
props: {
code: {
type: String,
default: ''
}
},
data () {
return {
html: '',
js: '',
css: ''
}
},
}
</script>
<style>
.bbb{
color: aqua;
}
</style>
代码分割器的工具类splitCode
export const getSource = (source, type) => {
const regex = new RegExp(`<${type}[^>]*>`);
let openingTag = source.match(regex);
if (!openingTag) return '';
else openingTag = openingTag[0];
return source.slice(source.indexOf(openingTag) + openingTag.length, source.lastIndexOf(`</${type}>`));
}
export const splitCode = (codeStr) => {
const script = getSource(codeStr, 'script').replace(/export default/, 'return ');
const css = getSource(codeStr, 'style');
const template = getSource(codeStr, 'template');
if(css) {
const style = document.createElement('style');
style.type = 'text/css';
// style.id = this.id;
style.innerHTML = css;
document.getElementsByTagName('head')[0].appendChild(style);
}
return {
...new Function(script)(), template
}
}
一个简单的远程调用模块就完成了