欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

vuex 中插件的编写案例解析

程序员文章站 2022-11-20 09:03:10
一、 1、第一步 const myplugin = store => { // 当 store 初始化后调用 store.subscribe((m...

一、

1、第一步

const myplugin = store => {
 // 当 store 初始化后调用
 store.subscribe((mutation, state) => {
 // 每次 mutation 之后调用
 // mutation 的格式为 { type, payload }
 });
};

2、第二步

const store = new vuex.store({
 // ...
 plugins: [myplugin]
});

二、编写一个打印日志的插件

1、函数的书写

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 数据持久化

1、函数的书写

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

2

总结

以上所述是小编给大家介绍的vuex 中插件的编写案例解析,希望对大家有所帮助