VueX的熱更替你知道多少?

前言

我們在使用Vuex的時候,會時不時的更改Vuex內(nèi)的數(shù)據(jù),但是頁面不會隨之更新,如果數(shù)據(jù)量大,一個數(shù)據(jù)依賴另一個數(shù)據(jù)的話,這樣我們要是再刷新頁面的話會把以前依賴的數(shù)據(jù)清空,效率特別低。所以,今天我總結(jié)了怎么實現(xiàn)Vuex熱更替的功能。
實現(xiàn)

首先,我們這里使用了Vue CLI3。在根目錄下的src目錄下我們有一個存放Vuex的文件夾叫做store文件夾。首先我們分割成幾個模塊。
















下面我們把它們分別引入,這里沒有分割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){
  // 跟上面一樣,寫入對應(yīng)的分割模塊路徑
    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')


作者:Vam的金豆之路

主要領(lǐng)域:前端開發(fā)

我的微信:maomin9761

微信公眾號:前端歷劫之路