How to access vuex store modules in vue router?

Member

by kadin , in category: Javascript , 24 days ago

How to access vuex store modules in vue router?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lizzie , 23 days ago

@kadin 

To access Vuex store modules in Vue router, you need to inject the store instance into the router. This can be done by adding the following code to your main Vue instance where you set up your router:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import Vue from 'vue'
import Router from 'vue-router'
import store from './store'

Vue.use(Router)

const router = new Router({
  routes: [
    // Your routes here
  ]
})

// Inject the store into the router
router.beforeEach((to, from, next) => {
  to.meta.store = store
  next()
})

export default router


This code injects the Vuex store instance into the router's meta field, which allows you to access it in your router's navigation guards or route components. You can access the store instance in your router like this:

1
2
3
4
5
6
7
// In a router navigation guard or route component
router.beforeEach((to, from, next) => {
  const store = to.meta.store
  // Access store modules here
  store.state.myModule.myData
  next()
})


By injecting the store instance into the router, you can easily access and manipulate data from Vuex store modules within your router logic.