我在Vue.js项目的main.js中声明了一个全局变量。
Vue.prototype.$API = "myapihere"
我想在任何地方都使用它。
使用 this.$API 可以正常工作。
但在 Vuex 中它不起作用。
console.log(this.$API);
这里 this.$API 是未定义。
我如何在 Vuex 中使用我的 $API。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
我正在使用 Vue 3,并且
Vue.prototype.$foo似乎已在此版本中删除。我还发现在我的 VueX 版本中没有this._vm。我探索了 Provide / Inject 方法,这是由Vue 3 文档。这对于从我的组件内访问全局变量非常有效,但我无法从商店内访问它们。
我寻求的解决方案是在 Vue 上使用 globalProperties
store上的对象和标准属性,并在安装应用程序之前设置它们。main.js:import store from './store/index'; import App from './App.vue'; // Load custom globals import conf from '@/inc/myapp.config'; const app = createApp(App) .use(store); // Register globals in app and store app.config.globalProperties.$conf = conf; store.$conf = conf; app.mount('#app');我喜欢这一点的是,我可以在存储和组件中以相同的方式访问全局变量。
在组件中:
export default { data() { return { }; }, created() { console.log( this.$conf.API_URL ); }, }...您可以通过操作、突变和 getter 以相同的方式访问
this.$conf.API_URL。一旦我找到了这个解决方案,我就不再需要从商店内访问整个 Vue 实例,但如果您出于某种原因需要它,您可以分配
store.$app = app;在main.js中的同一位置。Vue 2 和 Vuex 3 答案
在商店中可以通过访问
this._vm来访问vue实例const store = new Vuex.Store({ mutations: { test(state) { console.log(this._vm); } } });