将路由器参数转换为Vuex操作 [英] Getting router params into Vuex actions
问题描述
我想将路由器参数传递给Vuex操作,而不必为大型表格中的每一个动作提取它们:
I would like to pass router params into Vuex actions, without having to fetch them for every single action in a large form like so:
edit_sport_type({ rootState, state, commit }, event) {
const sportName = rootState.route.params.sportName <-------
const payload = {sportName, event} <-------
commit(types.EDIT_SPORT_TYPE, payload)
},
或者是这样,
edit_sport_type({ state, commit, getters }, event) {
const payload = {sportName, getters.getSportName} <-------
commit(types.EDIT_SPORT_TYPE, payload)
},
或更糟糕的是:从每个派遣中获取组件道具中的参数并将它们传递给派遣。
Or even worse: grabbing params from component props and passing them to dispatch, for every dispatch.
有没有办法在一大堆行动中抽象出来?
Is there a way to abstract this for a large set of actions?
或者也许是突变本身的替代方法?
Or perhaps an alternative approach within mutations themselves?
推荐答案
从vuex store action获取params,导入vue-router实例,然后从vuex store action访问路由器实例的params。
to get params from vuex store action, import vue-router instance, then access params of the router instance from vuex store action.
下面的示例实现:
路由器在 src / router / index.js
:
import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes'
Vue.use(VueRouter)
const router = new VueRouter({
mode: 'history',
routes
})
export default router
```
在vuex商店导入路由器:
import the router at vuex store:
import router from '@/router'
-------
然后访问在vuex动作函数中的params,在本例中为id,如下所示:
then access params at vuex action function, in this case "id", like below:
router.currentRoute.params.id
这篇关于将路由器参数转换为Vuex操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!