When working with Vue components, it's simple to utilize imported libraries like vue-router
. I can easily retrieve the necessary route parameter using this.$route.params.myVar
. However, when attempting to do the same within a Vuex module, an error occurs:
TypeError: Cannot read property 'myVar' of undefined
. How can I extend the Vue object I defined in my main.js
to my modules?
Below is 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 here's my my.module.js
:
export default {
namespaced: true,
state: {
...
},
mutations: {
...
},
actions: {
someAction() {
console.log(this.$route.params.myVar)
}
}
}
It becomes apparent that this
is not defined. Attempts were made to instantiate a new Vue object at the beginning of the module:
var vm = new Vue()
However, changing this
to vm
resulted in a similar error:
Cannot read property 'myVar' of undefined
. Another effort involved re-instantiating the route
class within the module:
import route from 'vue-router'
Adapting the code to route.params.myVar
still led to the error message:
Cannot read property 'myVar' of undefined
.