Heim  >  Fragen und Antworten  >  Hauptteil

Zugriff auf Vue-Instanzen in Vuex: eine Schritt-für-Schritt-Anleitung

Ich habe in main.js meines Vue.js-Projekts eine globale Variable deklariert.

Vue.prototype.$API = "myapihere"

Ich möchte es überall verwenden. Es funktioniert gut mit this.$API.

Aber in Vuex funktioniert es nicht.

console.log(this.$API);

Hier this.$API ist undefiniert.

Wie verwende ich mein $API in Vuex.

P粉878510551P粉878510551362 Tage vor679

Antworte allen(2)Ich werde antworten

  • 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 中的同一位置。

    Antwort
    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);
        }
      }
    });
    

    Antwort
    0
  • StornierenAntwort