Reputation: 759
In Vue components, I can easily use imported libraries, such as vue-router
. I can access the route parameter I need with this.$route.params.myVar
. However, if I try to do the same within a Vuex module, I get the error: TypeError: Cannot read property 'myVar' of undefined
. How can I extend the Vue object I defined in my main.js
to my modules?
Here's my main.js
:
import router from './router'
import Vuex from 'vuex'
import myModule from './my.module';
Vue.use(Vuex)
// Register VueX modules
const store = new Vuex.Store({
modules: {
myModule
}
})
new Vue({
router,
render: h => h(App),
store
}).$mount('#app')
And my.module.js
:
export default {
namespaced: true,
state: {
...
},
mutations: {
...
},
actions: {
someAction() {
console.log(this.$route.params.myVar)
}
}
}
Obviously, this
isn't defined. I tried instantiating a new Vue object at the top of my module like so:
var vm = new Vue()
And changing this
to vm
, but I get a similar Cannot read property 'myVar' of undefined
error. I also tried re-instantiating the route
class at the the module:
import route from 'vue-router'
And changing my failing code to route.params.myVar
, but I still get the Cannot read property 'myVar' of undefined
error.
Upvotes: 0
Views: 205
Reputation: 1185
The way I see it, you have two options.
For the second option make sure to import your router declaration and not the library. For example.
import router from '@/router'
router.currentRoute.params.myVar
Upvotes: 1