Search code examples
vue.jsvuexvuejs3vuex4

Access app.config.globalProperties in vuex store


I got a vuex store like this:

const state = {
    status: '',
};

const getters = {
   //...
};

const actions = {

 // ...
};

const mutations = {
// ... 
};

export default {
    namespaced: true,
    state,
    getters,
    actions,
    mutations,
}

Now I'd like to access app.config.globalProperties.$notify

In Vue.js2 I was using something like Vue.prototype.$notify, but this is not working anymore.

$notify is also provided like this:

app.use(routes)
  .provide('notify', app.config.globalProperties.$notify)
  .mount('#app')

Unfortunately I did not find any information about this in the docs yet.

So my question: How can I either inject $notify or access app.config.globalProperties within this store?


Solution

  • From your store and its modules, you could return a store factory -- a function that receives the application instance from createApp and returns a store:

    // store/modules/my-module.js
    const createStore = app => {
      const mutations = {
        test (state, { committedItem }) {
          app.config.globalProperties.$notify('commited item: ' + committedItem)
        }
      }
    
      return {
        namespaced: true,
        //...
        mutations,
      }
    }
    
    export default app => createStore(app)
    
    // store/index.js
    import { createStore } from 'vuex'
    import myModule from './modules/my-module'
    
    export default app =>
      createStore({
        modules: {
          myModule: myModule(app)
        }
      })
    

    Then use the store factory like this:

    // main.js
    import { createApp } from 'vue'
    import App from './App.vue'
    import createStore from './store'
    
    const app = createApp(App)
    app.use(createStore(app)).mount('#app')
    

    demo