溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Vuex的熱更替的實現方法

發布時間:2020-07-18 14:00:58 來源:億速云 閱讀:171 作者:小豬 欄目:web開發

這篇文章主要講解了Vuex的熱更替的實現方法,內容清晰明了,對此有興趣的小伙伴可以學習一下,相信大家閱讀完之后會有幫助。

前言

我們在使用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')

一些其他api

// store.registerModule({ //動態添加模塊
// })

// 相當于getter
// store.watch((state)=>state.count+1,(newCount)=>{
//  console.log('new count watched , '+newCount)
// })

// mutation被調用時
// store.subscribe((mutation,state)=>{
//  console.log(mutation.type)
//  console.log(mutation.payload)
// })

// action被調用時
// store.subscribeAction((action,state)=>{
//  console.log(action.type)
//  console.log(action.payload)
// }) 

看完上述內容,是不是對Vuex的熱更替的實現方法有進一步的了解,如果還想學習更多內容,歡迎關注億速云行業資訊頻道。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女