Home > Software engineering >  How to access Vue 3 global properties from the store
How to access Vue 3 global properties from the store

Time:12-16

In Vue 2 I used to import Vue and access global properties like this (from the store):

import Vue from 'vue'    
Vue.config.myGlobalProperty

According to the new documentation, in Vue 3 the global properties are declared using the app object returned by createApp:

const app = createApp({})
app.config.globalProperties.myGlobalProperty

And then accessed in the child component by simply calling this.myglobalProperty

But how to access that global property from the store? I tried exporting/importing the app object but it doesn't work (probably due to the app being created after its import in the store).

With Vue 2 I used to use global properties in the store like this:
Declaration in the main.js file:

import Vue from 'vue'
Vue.config.myglobalProperty = 'value'

Usage in the store:

import Vue from 'vue'
Vue.config.myglobalProperty

Is there a good way to do that in Vue3?

I noticed a better way to provide/inject properties but it works with child component only and not with the store.

CodePudding user response:

You could pass the app instance to a store factory:

// store.js
import { createStore as createVuexStore } from 'vuex'

export const createStore = (app) => {
  return createVuexStore({
    actions: {
      doSomething() {
        if (app.config.globalProperties.myGlobal) {
          //...
        }
      }
    }
  })
}

And use it like this:

// main.js
import { createApp } from 'vue'
import { createStore } from './store'

const app = createApp({})
const store = createStore(app)
app.use(store)
app.mount('#app')

CodePudding user response:

If you do not use Vuex, etc., you can easily create your store via provide/inject on the application itself, as in the example (the example is simplified for understanding):

const createState = () => reactive({counter: 0, anyVariable: 1});
const state = createState();
const key = 'myState';

// example of reactivity outside a component
setInterval(() => {
  state.counter  ;
}, 1000);

const app = createApp({});
app.provide('myState', state); // provide is used on the whole application

As you can see, your own store can be completely used outside the component.

Inside components, you can use (example):

  setup() {
  ...
    const globalState = inject('myStore'); // reactive => {counter: 0, anyVariable: 1}
  ...
    return {globalState, ...}
  }

Accordingly, you can have multiple stores in multiple Vue applications.

I hope this example will help you somehow.

  • Related