带有外部配置文件的 Vue js
Vue js with an external configuration file
我想知道是否可以让 Vue 应用程序读取外部配置文件。我想象我在其中部署应用程序,将应用程序与配置文件一起发送;此时应该可以更改外部文件中的配置,而不必重建整个应用程序。有什么办法可以达到那个结果吗?现在我正在使用一个单独的 Vuex 商店,但我无法在不重建整个应用程序的情况下更改配置。
我忘了说这个项目是用 Vue CLI 做的。
我有一个由节点提供的路由,其中 returns 一个动态创建的 JS 文件并定义了一个全局对象,我在其中存储该配置。不依赖于 Vue。
在index.html
中:
<script type="text/javascript" src="config.js"></script>
在node
(服务器端):
app.get('/config.js', (request, reply) => {
reply.header('Content-Type', 'application/javascript');
reply.send(`MyConfig = ${JSON.stringify(config)}`);
});
在组件中(或其他任何地方):
{
data: () => ({
someField: MyConfig.someField
})
}
您可以从 public 文件夹中获取 config.json
,然后在解析回调中加载您的 Vue 应用程序
将您的配置密钥放入 /public/config.json
文件
{
"KEY": "value"
}
然后在您的 /src/main.js
文件中
fetch(process.env.BASE_URL + "config.json")
.then((response) => response.json())
.then((config) => {
Vue.prototype.$config = config
new Vue({
router,
store,
render: (h) => h(App)
}).$mount("#app")
})
您将在整个应用程序范围内加载您的配置。然后你可以只使用
mounted() {
this.$config.KEY // "value"
}
在你的 Vue 组件中
这是我的做法:
在您的 public 文件夹中创建一个 config.js 文件,其中包含您想要的设置:
window.VUE_APP_API_KEY = 'blahblahblah';
然后在您的 public/index.html 中将以下行添加到您的头部部分:
<script type="text/javascript">
var cachebuster = Math.round(new Date().getTime() / 1000);
document.write('<scr' + 'ipt type="text/javascript" src="<%= BASE_URL %>config.js?cb=' + cachebuster + '"></scr' + 'ipt>');
</script>
然后在您的 VUE 应用程序中,您只需调用 window.VUE_APP_API_KEY。简单,快速:)
我想知道是否可以让 Vue 应用程序读取外部配置文件。我想象我在其中部署应用程序,将应用程序与配置文件一起发送;此时应该可以更改外部文件中的配置,而不必重建整个应用程序。有什么办法可以达到那个结果吗?现在我正在使用一个单独的 Vuex 商店,但我无法在不重建整个应用程序的情况下更改配置。
我忘了说这个项目是用 Vue CLI 做的。
我有一个由节点提供的路由,其中 returns 一个动态创建的 JS 文件并定义了一个全局对象,我在其中存储该配置。不依赖于 Vue。
在index.html
中:
<script type="text/javascript" src="config.js"></script>
在node
(服务器端):
app.get('/config.js', (request, reply) => {
reply.header('Content-Type', 'application/javascript');
reply.send(`MyConfig = ${JSON.stringify(config)}`);
});
在组件中(或其他任何地方):
{
data: () => ({
someField: MyConfig.someField
})
}
您可以从 public 文件夹中获取 config.json
,然后在解析回调中加载您的 Vue 应用程序
将您的配置密钥放入 /public/config.json
文件
{
"KEY": "value"
}
然后在您的 /src/main.js
文件中
fetch(process.env.BASE_URL + "config.json")
.then((response) => response.json())
.then((config) => {
Vue.prototype.$config = config
new Vue({
router,
store,
render: (h) => h(App)
}).$mount("#app")
})
您将在整个应用程序范围内加载您的配置。然后你可以只使用
mounted() {
this.$config.KEY // "value"
}
在你的 Vue 组件中
这是我的做法:
在您的 public 文件夹中创建一个 config.js 文件,其中包含您想要的设置:
window.VUE_APP_API_KEY = 'blahblahblah';
然后在您的 public/index.html 中将以下行添加到您的头部部分:
<script type="text/javascript">
var cachebuster = Math.round(new Date().getTime() / 1000);
document.write('<scr' + 'ipt type="text/javascript" src="<%= BASE_URL %>config.js?cb=' + cachebuster + '"></scr' + 'ipt>');
</script>
然后在您的 VUE 应用程序中,您只需调用 window.VUE_APP_API_KEY。简单,快速:)