如何實(shí)現(xiàn)Vuex的熱更新
前言
我們?cè)谑褂肰uex的時(shí)候,會(huì)時(shí)不時(shí)的更改Vuex內(nèi)的數(shù)據(jù),但是頁面不會(huì)隨之更新,如果數(shù)據(jù)量大,一個(gè)數(shù)據(jù)依賴另一個(gè)數(shù)據(jù)的話,這樣我們要是再刷新頁面的話會(huì)把以前依賴的數(shù)據(jù)清空,效率特別低。所以,今天我總結(jié)了怎么實(shí)現(xiàn)Vuex熱更替的功能。
實(shí)現(xiàn)
首先,我們這里使用了Vue CLI3。在根目錄下的src目錄下我們有一個(gè)存放Vuex的文件夾叫做store文件夾。首先我們分割成幾個(gè)模塊。
下面我們把它們分別引入,這里沒有分割actions,不過與其他屬性同理,這里有不做介紹。下面我們?cè)趇ndex.js編輯下面代碼:
- import Vuex from 'vuex'
- // 引入分割的模塊
- import state from './state/state'
- import mutations from './mutations/mutations'
- import getters from './getters/getters'
- export default ()=>{
- // 這里需要賦給一個(gè)store變量
- const store = new Vuex.Store({
- state:state,
- mutations:mutations,
- getters:getters
- })
- // 熱更新模塊
- if(module.hot){
- // 跟上面一樣,寫入對(duì)應(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')
結(jié)語
以上,就完成了Vuex的熱更替功能。需要注意的是,直接在state中更改是看不到效果的哦!謝謝閱讀。