我想知道是否可以让 Vue 应用程序读取外部配置文件。我想象我在其中部署应用程序,将应用程序与配置文件一起发送;此时应该可以更改外部文件中的配置,而无需重建整个应用程序。有什么办法我可以达到这个结果吗?现在我使用一个单独的 Vuex 存储,但如果不重建整个应用程序,我无法更改配置。
我忘了提及该项目是用 Vue CLI 制作的。
您可以从公共文件夹中获取
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 组件中
2022 年 11 月 23 日更新(添加 Vue 3 版本):
// VUE 3 Version
const app = createApp(App)
fetch(process.env.BASE_URL + "config.json")
.then((response) => response.json())
.then((config) => {
// either use window.config
window.config = config
// or use [Vue Global Config][1]
app.config.globalProperties.config = config
// FINALLY, mount the app
app.mount("#app")
})
我是这样做的:
使用所需的设置在公共文件夹中创建 config.js 文件:
window.VUE_APP_API_KEY = 'blahblahblah';
然后在 public/index.html 中将以下行添加到 head 部分:
<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即可。简单、快捷:)
我有一个由节点提供的路由,它返回动态创建的 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
})
}
受 @Hammad 的启发,此方法适用于使用 TypeScript 和 Composition API 以及 app.provide() 机制的 Vue.js 3。
将配置密钥放入
/public/config.json
文件中:
{
"KEY": "value"
}
然后,在您的
/src/main.ts
文件中:
fetch(import.meta.env.BASE_URL + 'config.json')
.then((response) => response.json())
.then((config) => {
for (const key in config) {
app.provide(key, config[key])
}
app.mount('#app')
})
最后,读取组件内部的配置:
<script setup lang="ts">
import { inject } from 'vue'
...
const config_value = inject('KEY')