Reputation: 619
I am trying to learn Vuex and making authentication module. I was following some tutorial and got to the point when I want to use store in router. I am importing my store on the top of the router index.js, however I am guessing it's not importing my store as I can't access e.g. getters (undefined).
Store works fine in vue components. Why is that happening ? is it because store is not properly initialised when router is created ? According to tutorial that works fine.
router/index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes'
import store from '../store'
Vue.use(VueRouter)
/*
* If not building with SSR mode, you can
* directly export the Router instantiation
*/
export default function(/* { store, ssrContext } */) {
const Router = new VueRouter({
scrollBehavior: () => ({ x: 0, y: 0 }),
routes,
// Leave these as is and change from quasar.conf.js instead!
// quasar.conf.js -> build -> vueRouterMode
// quasar.conf.js -> build -> publicPath
mode: process.env.VUE_ROUTER_MODE,
base: process.env.VUE_ROUTER_BASE,
})
Router.beforeEach((to, from, next) => {
if(to.matched.some(record => record.meta.requiresAuth)) {
if (store.getters.isLoggedIn) {
next()
return
}
next('/login')
} else {
next()
}
})
return Router
}
and store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
// import example from './module-example'
Vue.use(Vuex)
/*
* If not building with SSR mode, you can
* directly export the Store instantiation
*/
import state from './state'
import getters from './getters'
import mutations from './mutations'
import actions from './actions'
export default function(/* { ssrContext } */) {
const Store = new Vuex.Store({
modules: {
// example
},
namespaced: true,
getters,
mutations,
actions,
state,
// enable strict mode (adds overhead!)
// for dev mode only
strict: process.env.DEV,
})
return Store
}
Upvotes: 2
Views: 4202
Reputation: 1641
As at 24th Feb 22 you can now...
at the top of router.js
import { useStore } from 'vuex'
and then within the module function
const store = useStore()
you then have access to store.state
and can store.commit('ANY_MUTATION',data)
etc,etc
Upvotes: 0
Reputation: 115
You do not need to modified your default Quasar store/index.js
Just use it as a Promise function:
import store from '../store'
....
if (store().getters['auth/isLoggedIn']) {
next()
return
}
Upvotes: 5
Reputation: 619
I will answer it myself. My store doesn't have typical export default store,
so i modified it to below, and it works fine.
const store = new Vuex.Store({
modules: {
authentication
},
namespaced: true,
strict: process.env.DEV,
})
export default store
Upvotes: 1