前言

我们在使用Vuex的时候,会时不时的更改Vuex内的数据,但是页面不会随之更新,如果数据量大,一个数据依赖另一个数据的话,这样我们要是再刷新页面的话会把以前依赖的数据清空,效率特别低。所以,今天我总结了怎么实现Vuex热更替的功能。

实现

首先,我们这里使用了Vue CLI3。在根目录下的src目录下我们有一个存放Vuex的文件夹叫做store文件夹。首先我们分割成几个模块。

Vuex的热更替你知道多少?_数据

下面我们把它们分别引入,这里没有分割​​actions​​,不过与其他属性同理,这里有不做介绍。下面我们在​​index.js​​编辑下面代码:

import Vuex from 'vuex'
// 引入分割的模块
import state from './state/state'
import mutations from './mutations/mutations'
import getters from './getters/getters'

export default ()=>{
// 这里需要赋给一个store变量
const store = new Vuex.Store({
state:state,
mutations:mutations,
getters:getters
})
// 热更新模块
if(module.hot){
// 跟上面一样,写入对应的分割模块路径
module.hot.accept([
'./state/state',
'./mutations/mutations',
'./getters/getters'
],()=>{
// 开启热更替
const newState = require('./state/state').default
const newMutations = require('./mutations/mutations').default
const newGetters = require('./getters/getters').default
store.hotUpdate({
state:newState,
mutations:newMutations,
getters:newGetters
})
})
}

return store
}

我们还需要在​​main.js​​修改:

import Vue from 'vue'
import App from './App.vue'
import Vuex from 'vuex'
import createStore from './store/index.js'

Vue.config.productionTip = false

Vue.use(Vuex)
const store=createStore();

new Vue({
store,
render: h => h(App)
}).$mount('#app')

结语

以上,就完成了Vuex的热更替功能。需要注意的是,直接在state中更改是看不到效果的哦!谢谢阅读。


作者:​Vam的金豆之路 主要领域:​前端开发 微信公众号:​前端历劫之路Vuex的热更替你知道多少?_微信公众号_02