Search code examples
vue.jsvuexvuejs3quasar-framework

Accessing Vuex Module in JS file


I am using Quasar framework + Vue3 and importing a module in my Vuex Store. It works fine when I consume it in a Vue file but how can access it from a JS file? I can log the states in the settings module, but everything is blank. It seems like it wasnt initialized yet, but how can I get the initialized and filled up store? Also, when Vuex store is updated, and I try to fetch the updated data from the JS file, it just shows blank/null.

import { createStore } from 'vuex'
import { settings } from './settings'

export default function () {
  const Store = createStore({
    modules: {
      settings
    },
    state: {
      isProdBuild: process.env.NODE_ENV === 'production'
    }
  })
  return Store
}

import useStore from '../store'

const store = useStore()
export function sample () {
  console.log(store.state.isProdBuild) // this works
  console.log(store.state.settings.sampleParam) // doesnt work, seems like the value isnt initialized
}

Help! Thanks!


Solution

  • Found a workaround for this issue.

    In my JS file, I just added a setter function to set the store.

    let store = null
    export setStore(val) {
       store = val
    }
    
    export function sample () {
      console.log(store.state.isProdBuild)
      console.log(store.state.settings.sampleParam)
    }
    

    Then in my Vue file:

    import { onMounted } from 'vue'
    import { useStore } from 'vuex'
    import { setStore, sample } from 'sample-file.js'
    
    const $store = useStore()
    
    onMounted(() => {
      setStore($store)
    })
    

    Then calling whatever method from sample-file.js that accesses the Vuex store works now and the state is always updated.