搜索

首页  >  问答  >  正文

在 Vuex 中访问 Vue 实例:分步指南

我在Vue.js项目的main.js中声明了一个全局变量。

Vue.prototype.$API = "myapihere"

我想在任何地方都使用它。 使用 this.$API 可以正常工作。

但在 Vuex 中它不起作用。

console.log(this.$API);

这里 this.$API未定义

我如何在 Vuex 中使用我的 $API

P粉878510551P粉878510551508 天前860

全部回复(2)我来回复

  • P粉194919082

    P粉1949190822023-10-23 13:35:05

    我正在使用 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 中的同一位置。

    回复
    0
  • P粉054616867

    P粉0546168672023-10-23 11:53:45

    Vue 2 和 Vuex 3 答案

    在商店中可以通过访问this._vm来访问vue实例

    const store = new Vuex.Store({
      mutations: {
        test(state) {
          console.log(this._vm);
        }
      }
    });
    

    回复
    0
  • 取消回复