我在调用 Vue 之前在我的 main.js 文件中设置配置:
Vue.prototype.$api_url = process.env.NODE_ENV === 'production' ? 'https://api.xxx.com' : 'https://yyy.test:8443'
如果我在任何 Vue 文件中访问 this.$api_url
,它就会工作。
但是在store.js(Vuex)中,渲染的是另一个Vue实例,所以我无法访问this.$api_url
。
如何在文件和 Vue.use(configs.js)
中设置配置?
为了在 main.js/store.js
中获取它的变量,我应该在配置文件中做什么?
谢谢。
最佳答案
制作一个独立的 config.js 文件并从该文件中导出您的配置对象。并在需要配置的地方导入配置。 如果您希望在所有 Vue 组件中提供相同的配置,您也可以将相同的配置分配给 Vue 的原型(prototype)。
更新:
所以这里是你如何做到这一点:
在你的 config.js 中
let config;
if (process.env.NODE_ENV === "production") {
config = {
$api_url: "https://api.xxx.com",
timeoutDuration: 30000,
someOtherProps: 'xyz'
};
} else {
config = {
$api_url: "https://yyy.test:8443",
timeoutDuration: 1000,
someOtherProps: 'abc'
};
}
export { config }
在你的 main.js 中
import { config } from 'config';
Vue.prototype.appConfig = config
使用 this.appConfig.$api_url
任何你想在 .vue 文件中使用的方式
在你的 store.js 中
import { config } from 'config';
使用 config.$api_url
任何你想使用的方式
关于vue.js - 如何将配置文件导入 Vue.JS+Vuex,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53057546/