Skip to content
This repository has been archived by the owner on Feb 9, 2021. It is now read-only.

给 vuex store 添加热更新功能 #12

Open
lbwa opened this issue Apr 26, 2018 · 0 comments
Open

给 vuex store 添加热更新功能 #12

lbwa opened this issue Apr 26, 2018 · 0 comments
Labels
Code skill Skill from coding Vue.js Vue.js / Vue-router / Vue-cli / Vuex .etc

Comments

@lbwa
Copy link
Owner

lbwa commented Apr 26, 2018

import Vuex from 'vuex'
import createLogger from 'vuex/dist/logger'

import defaultState from './state/state'
import getters from './getters/getters'
import mutations from './mutations/mutations'
import * as actions from './actions/actions'

const debug = process.env.NODE_ENV === 'development'

// ssr 时,保证每次渲染去掉对之前的 store 引用,对应一个新的 store,以防止内存溢出。
/* eslint-disable no-new */
export default () => {
  const store = new Vuex.Store({
    state: defaultState,
    getters,
    mutations,
    actions,

    // 限定只能通过  mutations 修改 state,不应用于生产环境
    strict: debug,

    // 使用提交 mutations 和 actions 在控制台输出的插件
    plugins: debug ? [createLogger()] : []
  })

  // 给 store 添加热模块加载功能
  if (module.hot) {
    module.hot.accept([
      './state/state',
      './getters/getters',
      './mutations/mutations',
      './actions/actions'
    ], () => {
      // import 语句不能写在业务代码块中,只能写在外部
      const newState = require('./state/state').default
      const newGetters = require('./getters/getters').default
      const newMutations = require('./mutations/mutations').default
      const newActions = require('./actions/actions').default

      store.hotUpdate({
        state: newState,
        getters: newGetters,
        mutations: newMutations,
        actions: newActions
      })
    })
  }
  return store
}
@lbwa lbwa added Code skill Skill from coding Vue.js Vue.js / Vue-router / Vue-cli / Vuex .etc labels Apr 26, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Code skill Skill from coding Vue.js Vue.js / Vue-router / Vue-cli / Vuex .etc
Projects
None yet
Development

No branches or pull requests

1 participant