如何访问 Vuex 模块中的 Vue 对象?
How do I access the Vue object within a Vuex module?
在Vue组件中,我可以轻松使用导入的库,比如vue-router
。我可以使用 this.$route.params.myVar
访问我需要的路由参数。但是,如果我尝试在 Vuex 模块中执行相同的操作,则会收到错误消息:TypeError: Cannot read property 'myVar' of undefined
。如何将我在 main.js
中定义的 Vue 对象扩展到我的模块?
这是我的 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')
和my.module.js
:
export default {
namespaced: true,
state: {
...
},
mutations: {
...
},
actions: {
someAction() {
console.log(this.$route.params.myVar)
}
}
}
显然,this
未定义。我尝试在我的模块顶部实例化一个新的 Vue 对象,如下所示:
var vm = new Vue()
并将 this
更改为 vm
,但我收到类似的 Cannot read property 'myVar' of undefined
错误。我还尝试在模块中重新实例化 route
class:
import route from 'vue-router'
并将我的失败代码更改为 route.params.myVar
,但我仍然收到 Cannot read property 'myVar' of undefined
错误。
在我看来,你有两个选择。
- 从外到内传递param.myvar vuex 动作
- 将路由器导入vuex模块并使用
对于第二个选项,请确保导入您的路由器声明而不是库。例如。
import router from '@/router'
router.currentRoute.params.myVar
在Vue组件中,我可以轻松使用导入的库,比如vue-router
。我可以使用 this.$route.params.myVar
访问我需要的路由参数。但是,如果我尝试在 Vuex 模块中执行相同的操作,则会收到错误消息:TypeError: Cannot read property 'myVar' of undefined
。如何将我在 main.js
中定义的 Vue 对象扩展到我的模块?
这是我的 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')
和my.module.js
:
export default {
namespaced: true,
state: {
...
},
mutations: {
...
},
actions: {
someAction() {
console.log(this.$route.params.myVar)
}
}
}
显然,this
未定义。我尝试在我的模块顶部实例化一个新的 Vue 对象,如下所示:
var vm = new Vue()
并将 this
更改为 vm
,但我收到类似的 Cannot read property 'myVar' of undefined
错误。我还尝试在模块中重新实例化 route
class:
import route from 'vue-router'
并将我的失败代码更改为 route.params.myVar
,但我仍然收到 Cannot read property 'myVar' of undefined
错误。
在我看来,你有两个选择。
- 从外到内传递param.myvar vuex 动作
- 将路由器导入vuex模块并使用
对于第二个选项,请确保导入您的路由器声明而不是库。例如。
import router from '@/router'
router.currentRoute.params.myVar