Access Vuex inside javascript



  • How to use vuex (like this.$store.getters …) in a .js file in the project as this.$store won’t work any more outside the vue component? I tried this https://stackoverflow.com/questions/63177298/call-vuex-getters-from-another-javascript-file but the getters returns a literal code.



  • @ilabutk it will work as long as you use function and not =>, i would import the store instance tho, just export it from your store/index.js. ie

    //store/index.js
    let store
    ...
      store = new Vuex(...)
    ...
    export { store }
    //some.js
    import { store } from 'src/store'
    


  • Thank you @metalsadman

    Here is /src/store/index.js

    let store = null
    
    export default function () {
      store = new Vuex.Store({
        modules: {
          user
        },
        plugins: [createPersistedState()], // to persist
    
        // enable strict mode (adds overhead!)
        // for dev mode only
        strict: process.env.DEV
      })
    
      return store
    }
    
    export { store }
    

    In another router-auth.js, I have

    import { store } from 'src/store'
    
    console.log(':: ROUTER-AUTH ::')
    console.log(store)
    

    It shows store null! // I just realized that the router-auth.js is a root file!! Could that be the reason? I tested your method in a regular .js file and it works. How can we let the router-auth.js boot after the store is created? Thank you!



  • @ilabutk what router-auth.js? If you are in a boot file then you shouldn’t import, just pass the store as a parameter in your export default function. https://quasar.dev/quasar-cli/boot-files#Introduction, same in router/index.js.



  • @metalsadman Of course!! Thank you. router-auth.js is a boot file that I added to check routes authentications). // Your tip on using Vuex in other .js files really helped!



  • The working version for others future reference::

    export default ({ router, store }) => {
      router.beforeEach((to, from, next) => {
        const loggedIn = store.getters['user/getLoggedIn']
        const guestRoutes = ['/', '/login', '/suport'] // guests route
    
        if (!loggedIn && !guestRoutes.includes(to.path)) {
          next('/login')
        } else {
          next()
        }
      })
    }
    

Log in to reply