VueX (五)热重载、TypeScript 支持、从 3.x 迁移到 4.0

VueX (五)热重载、TypeScript 支持、从 3.x 迁移到 4.0

1. 热重载

使用 webpack 的 Hot Module Replacement API,Vuex 支持在开发过程中热重载 mutation、module、action 和 getter。你也可以在 Browserify 中使用 browserify-hmr 插件

对于 mutation 和模块,你需要使用 store.hotUpdate() 方法:

// store.js
import {
    createStore } from 'vuex'
import mutations from './mutations'
import moduleA from './modules/a'

const state = {
    ... }

const store = createStore({
   
  state,
  mutations,
  modules: {
   
    a: moduleA
  }
})

if (module.hot) {
   
  // 使 action 和 mutation 成为可热重载模块
  module.hot.accept(['./mutations', './modules/a'], () => {
   
    // 获取更新后的模块
    // 因为 babel 6 的模块编译格式问题,这里需要加上 `.default`
    const newMutations = require('./mutations').default
    const newModuleA = require('./modules/a').default
    // 加载新模块
    store.hotUpdate({
   
      mutations: newMutations,
      modules: {
   
        a: newModuleA
      }
    })
  })
}

参考热重载示例 counter-hot

动态模块热重载

如果你仅使用模块==,你可以使用 require.context 来动态地加载或热重载所有的模块==。

// store.js
import {
    createStore } from 'vuex'

// 加载所有模块。
function loadModules() {
   
  const context = require.context("./modules", false, /([a-z_]+)\.js$/i)

  const modules = context
    .keys()
    .map((key) => ({
    key, name: key
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ChrisP3616

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值