Getting router params into Vuex actions

后端 未结 3 495
眼角桃花
眼角桃花 2021-02-07 12:08

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,          


        
3条回答
  •  悲哀的现实
    2021-02-07 12:42

    To my knowledge ( and I've looked into this for a project I'm working on ) no, there is not. The simplest way to do this is to abstract route fetching or anything you want to do to a service and use it in your vuex file or if you use modular approach import it in you actions.js file.

    so paramFetching.js file would look like this:

    export default {
      fetchRouteParams: function() {
        // do fetching
        // you should return a promise 
      }
    }
    

    Then import that into your vuex

    import service from 'paramFetching.js'
    

    And then make an action like so

    ...
    fetchParamsAction: function({commit}) {
      service.fetchRouteParams()
        .then( (response) => { // stuff gottten from service. you should o your commit here } )
        .catch( (error) => { // error handling } )
    }
    

    And then just dispatch this action and everything will be handled in an action. So it kinda isolates that from the rest of the code. This is just a general idea. I'm sorry if it's not clear enough. If I can help further, please ask.

提交回复
热议问题