這篇文章將為大家詳細講解有關vuex 中插件如何編寫,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。

一、官方文檔
1、第一步
const myPlugin = store => {
// 當 store 初始化后調用
store.subscribe((mutation, state) => {
// 每次 mutation 之后調用
// mutation 的格式為 { type, payload }
});
};2、第二步
const store = new Vuex.Store({
// ...
plugins: [myPlugin]
});二、編寫一個打印日志的插件
1、函數(shù)的書寫
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ù)的書寫
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、類似的第三方庫
1. vuex-persistedstate
2. vuex-persist
關于“vuex 中插件如何編寫”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
本文標題:vuex中插件如何編寫-創(chuàng)新互聯(lián)
當前網址:http://www.yijiale78.com/article34/phsse.html
成都網站建設公司_創(chuàng)新互聯(lián),為您提供面包屑導航、定制網站、營銷型網站建設、靜態(tài)網站、響應式網站、網站收錄
聲明:本網站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內容