Hot Reloading

Vuex supports hot-reloading mutations, modules, actions and getters during development, using webpack’s Hot Module Replacement APIHot Reloading - 图1 (opens new window). You can also use it in Browserify with the browserify-hmrHot Reloading - 图2 (opens new window) plugin.

For mutations and modules, you need to use the store.hotUpdate() API method:

  1. // store.js
  2. import Vue from 'vue'
  3. import Vuex from 'vuex'
  4. import mutations from './mutations'
  5. import moduleA from './modules/a'
  6. Vue.use(Vuex)
  7. const state = { ... }
  8. const store = new Vuex.Store({
  9. state,
  10. mutations,
  11. modules: {
  12. a: moduleA
  13. }
  14. })
  15. if (module.hot) {
  16. // accept actions and mutations as hot modules
  17. module.hot.accept(['./mutations', './modules/a'], () => {
  18. // require the updated modules
  19. // have to add .default here due to babel 6 module output
  20. const newMutations = require('./mutations').default
  21. const newModuleA = require('./modules/a').default
  22. // swap in the new modules and mutations
  23. store.hotUpdate({
  24. mutations: newMutations,
  25. modules: {
  26. a: newModuleA
  27. }
  28. })
  29. })
  30. }

Checkout the counter-hot exampleHot Reloading - 图3 (opens new window) to play with hot-reload.

Dynamic module hot reloading

If you use modules exclusively, you can use require.context to load and hot reload all modules dynamically.

  1. // store.js
  2. import Vue from 'vue'
  3. import Vuex from 'vuex'
  4. // Load all modules.
  5. function loadModules() {
  6. const context = require.context("./modules", false, /([a-z_]+)\.js$/i)
  7. const modules = context
  8. .keys()
  9. .map((key) => ({ key, name: key.match(/([a-z_]+)\.js$/i)[1] }))
  10. .reduce(
  11. (modules, { key, name }) => ({
  12. ...modules,
  13. [name]: context(key).default
  14. }),
  15. {}
  16. )
  17. return { context, modules }
  18. }
  19. const { context, modules } = loadModules()
  20. Vue.use(Vuex)
  21. const store = new Vuex.Store({
  22. modules
  23. })
  24. if (module.hot) {
  25. // Hot reload whenever any module changes.
  26. module.hot.accept(context.id, () => {
  27. const { modules } = loadModules()
  28. store.hotUpdate({
  29. modules
  30. })
  31. })
  32. }