config.json文件。 config.json
文件将包含该应用程序可以用来动态更改内容的一些字符串,例如显示给用户的视频文件和打印机的IP地址。// config.json
{
"brand": "eat",
"printerIP": "192.168.0.4"
}
我试图将文件放在资产文件夹和公共文件夹中。我尝试使用导入和需要语句将其导入scriptlang =“ ts”
// App.vue (<script lang="ts">)
const config = require('../public/config.json');
OR
import config from '../public/config.json';
I通过使用Axios将其像API一样处理,并且仅使用例如config.brand.。
// App.vue (<script lang="ts">)
import axios from 'axios';
@Provide() private brand: string = "";
axios
.get('.config.json')
.then(response => {
this.brand = response.data.brand;
})
OR
this.brand = config.brand;
不幸的是,数据仅在构建时间读取并将其编译为缩小的JavaScript。这意味着即使用户在构建应用程序后更新Config.json
中的变量,该应用也不会更新。我需要能够在构建文件中访问Config.json,更新一个值,然后在运行时读取新值,而无需再次构建项目。
可以这样做吗?
您认为应该将运行时配置放在public/
文件夹下,但不要导入它们。该导入将在构建时间期间得到解决,其结果将通过WebPack进行。而是使用fetch
通过http.
vue将
public
dist/
。您可以在运行时使用这样的HTTP请求访问它们:
const getRuntimeConfig = async () => {
const runtimeConfig = await fetch('/config');
return await runtimeConfig.json()
}
如果您想在多个vue组件中使用这些运行时配置而无需进行多个获取,那么请在驱动您的Vue应用程序(例如
src/main.js
)的主JavaScript文件中进行一次获取,并通过Vue Mixins共享结果,例如:
Vue.mixin({
data() {
return {
// Distribute runtime configs into every Vue component
BRAND: BRAND,
PRINTER_IP: json.printerIP
}
},
});