我终于用下面的方法实现了,也许这会对某人有所帮助.Suggestions highly appreciated!
Base App:
呈现所有子应用的基础应用有一个CustomAppContainer视图,该视图将子应用加载到一个div容器中.
<template>
<div id="customAppContainer"></div>
</template>
<script>
export default {
mounted() {
this.updateCustomAppContainer();
},
methods: {
updateCustomAppContainer() {
const fullRoute = this.$router.currentRoute.fullPath;
const routeSegments = fullRoute.split("/");
const appsIndex = routeSegments.indexOf("apps");
const appKey = routeSegments[appsIndex + 1];
document.getElementById(
"customAppContainer"
).innerHTML = `<object style="width: 100%; height:100%;" data="http://localhost:3000/subApps/${appKey}"></object>`;
}
},
watch: {
$route(to, from) {
this.updateCustomAppContainer();
}
}
};
</script>
此外,我在router的基础上增加了mode: 'history'
.
export default new Router({
mode: 'history',
routes: [
{
path: '/',
component: Home
},
{
path: '/apps/*',
component: CustomAppContainer,
}
]
})
我将该应用程序的构建文件放入名为base的文件夹中的生产目录
File Server:
我创建了一个静态Express文件服务器,它总是为基本应用程序的index.html个文件提供服务.但我也可以申请sub app的index.html文件.
const express = require('express');
const path = require('path');
const fs = require('fs');
const cors = require('cors');
const app = express();
const router = express.Router();
app.use(cors());
app.use(express.static(path.resolve(__dirname, '../base')));
fs.readdirSync(path.resolve(__dirname, '../apps')).forEach(appName => {
app.use(express.static(path.resolve(__dirname, `../apps/${appName}`)));
});
router.get('/subApps/:appName', function(req, res) {
res.sendFile(path.resolve(__dirname, `../apps/${req.params.appName}/index.html`));
});
router.get('*', function(req, res) {
res.sendFile(path.resolve(__dirname, '../base/index.html'));
});
app.use('/', router);
app.listen(3000, function() {
console.log('Fileserver listening on port 3000');
});
Custom App:
创建自定义应用程序时,我要做的就是扩展router配置
export default new Router({
base: '/my-first-custom-app/',
mode: 'history',
routes: [
{
path: '/',
component: PageOne,
},
{
path: '/two',
component: PageTwo,
},
],
});
并将index.html、main.js和App.vue中的#app
ID重命名为#customApp
.
此外,我将该子应用的构建文件放入名为apps的文件夹中的生产目录中.
这允许我创建多个应用程序,并将它们呈现到主应用程序容器的div容器中.子应用本身不一定是Vueapply.我可以用Jquery、Angular或React创建新的应用程序,甚至只是一个简单的应用程序.html文件.