Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting router params into Vuex actions

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)
},

Or like so,

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?

like image 750
softcode Avatar asked Feb 11 '17 17:02

softcode


1 Answers

To get params from vuex store action, import your vue-router's instance, then access params of the router instance from your vuex store via the router.currentRoute object.

Sample implementation below:

router at 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

import the router at vuex store:

import router from '@/router'

then access params at vuex action function, in this case "id", like below:

router.currentRoute.params.id
like image 119
Cipto HD Avatar answered Sep 20 '22 07:09

Cipto HD