genkio / blog

Stay hungry stay foolish
https://slashbit.github.io/blog/
0 stars 1 forks source link

Lesson learned upgrading Vuex from 0.8 to 2.2 #149

Open genkio opened 7 years ago

genkio commented 7 years ago

A side by side comparison of before and after the upgrade

Update build configuration

Vuex 2 takes the advantage of some new ES6 features, namely spread operator, hence we'll need first get our build environment ready to roll.

$ yarn add babel-preset-stage-3 --dev

Then update babel configuration file.babelrc

// before
{ "presets": ["stage-3"] }
// after
{ "presets": ["es2015", "stage-3"] }

If you're using eslint in the build process, you should probably update its configuration .eslintrc.json as well.

"parserOptions": {
  "sourceType": "module"
}
"parserOptions": {
  "sourceType": "module",
  "ecmaFeatures": {
    "experimentalObjectRestSpread": true
  }
}

Update vuex configuration

The only thing we changed in our project was the logger middle ware.

import createLogger from 'vuex/logger'

export default new Vuex.Store({
  // ...
  middlewares: debug ? [createLogger()] : [],
})
import createLogger from 'vuex/dist/logger'

export default new Vuex.Store({
  // ...
  plugins: debug ? [createLogger()] : [],
})

Update application logic

Before upgrade, state and actions were kept in the vuex property of all of our custom component.

import { changeCurrentPeriod } from 'store/actions'

vuex: {
  getters: {
    currentPeriod: state => state.currentPeriod
  },
  actions: {
    changeCurrentPeriod
  }
}

After upgrade, we'll need mapState and mapActions to pull state and actions into component computed property and methods.

import { mapState, mapActions } from 'vuex'

computed: mapState(['currentPeriod']),
methods: {
  ...mapActions(['changeCurrentPeriod']),
  // ...
}

Couple of things worth to point it out in the example above:

State

Actions

That said, here's the changes we made to our actions.

export const changeCurrentPeriod = ({ dispatch }, from, to) => {
  dispatch(types.CHANGE_CURRENT_PERIOD, from, to)
}
// notice, only one additional parameter is allowed here, 
// hence make the payload a object if you want pass mutation multiple things.
export const changeCurrentPeriod = ({ commit }, payload) => {
  commit(types.CHANGE_CURRENT_PERIOD, payload)
}