搜尋

首頁  >  問答  >  主體

在 Vuex 中存取 Vue 實例:逐步指南

我在Vue.js專案的main.js中宣告了一個全域變數。

Vue.prototype.$API = "myapihere"

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

但在 Vuex 中它不起作用。

console.log(this.$API);

這裡 this.$API未定義

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

P粉878510551P粉878510551508 天前861

全部回覆(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
  • 取消回覆