我在调用Vue之前在main.js文件中设置配置:
Vue.prototype.$api_url = process.env.NODE_ENV === 'production' ? 'https://api.xxx.com' : 'https://yyy.test:8443'
Run Code Online (Sandbox Code Playgroud)
如果我访问this.$api_url任何Vue文件,它都可以工作。
但是在store.js(Vuex)中,这是另一个呈现的Vue实例,因此我无法访问this.$api_url。
如何在文件中设置配置Vue.use(configs.js)呢?
我应该在configs文件中做什么以获取其变量main.js/store.js?
谢谢。
制作一个独立的config.js文件,然后从该文件导出配置对象。并在需要的地方导入配置。如果希望在所有Vue组件中提供相同的配置,也可以将相同的配置分配给Vue的原型。
更新:
因此,这是您可以执行的操作:
在你的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 }
Run Code Online (Sandbox Code Playgroud)
在你的main.js中
import { config } from 'config';
Vue.prototype.appConfig = config
Run Code Online (Sandbox Code Playgroud)
使用this.appConfig.$api_url您想要在.vue文件中使用的任何方式
在您的store.js中
import { config } from 'config';
Run Code Online (Sandbox Code Playgroud)
使用config.$api_url您想使用的任何方式