十年網(wǎng)站開(kāi)發(fā)經(jīng)驗(yàn) + 多家企業(yè)客戶(hù) + 靠譜的建站團(tuán)隊(duì)
量身定制 + 運(yùn)營(yíng)維護(hù)+專(zhuān)業(yè)推廣+無(wú)憂售后,網(wǎng)站問(wèn)題一站解決
這篇文章將為大家詳細(xì)講解有關(guān)vuex 中插件如何編寫(xiě),小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。
一、官方文檔
1、第一步
const myPlugin = store => { // 當(dāng) store 初始化后調(diào)用 store.subscribe((mutation, state) => { // 每次 mutation 之后調(diào)用 // mutation 的格式為 { type, payload } }); };
2、第二步
const store = new Vuex.Store({ // ... plugins: [myPlugin] });
二、編寫(xiě)一個(gè)打印日志的插件
1、函數(shù)的書(shū)寫(xiě)
import _ from 'lodash'; function logger() { return function(store) { let prevState = store.state; store.subscribe((mutations, state) => { console.log('prevState', prevState); console.log(mutations); console.log('currentState', state); prevState = _.cloneDeep(state); }); }; }
2、使用
export default new Vuex.Store({ modules: { ... }, strict: true, plugins: process.NODE_ENV === 'production' ? [] : [logger()] });
三、 vuex 數(shù)據(jù)持久化
1、函數(shù)的書(shū)寫(xiě)
function vuexLocal() { return function(store) { const local = JSON.parse(localStorage.getItem('myvuex')) || store.state; store.replaceState(local); store.subscribe((mutations, state) => { const newLocal = _.cloneDeep(state); sessionStorage.setItem('myvuex', JSON.stringify(newLocal)); }); }; }
2、使用
export default new Vuex.Store({ modules: { ... }, strict: true, plugins: process.NODE_ENV === 'production' ? [vuexLocal()] : [logger(), vuexLocal()] });
3、類(lèi)似的第三方庫(kù)
1. vuex-persistedstate
2. vuex-persist
關(guān)于“vuex 中插件如何編寫(xiě)”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺(jué)得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。