vuex 中插件的编写案例

1、官方文档

  • 一、第一步html

    const myPlugin = store => {
      // 当 store 初始化后调用
      store.subscribe((mutation, state) => {
        // 每次 mutation 以后调用
        // mutation 的格式为 { type, payload }
      });
    };
    复制代码
  • 二、第二步vue

    const store = new Vuex.Store({
      // ...
      plugins: [myPlugin]
    });
    复制代码

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

  • 一、函数的书写git

    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);
        });
      };
    }
    复制代码
  • 二、使用github

    export default new Vuex.Store({
      modules: {
        ...
      },
      strict: true,
      plugins: process.NODE_ENV === 'production' ? [] : [logger()]
    });
    复制代码

3、vuex数据持久化

  • 一、函数的书写vuex

    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));
        });
      };
    }
    复制代码
  • 二、使用npm

    export default new Vuex.Store({
      modules: {
        ...
      },
      strict: true,
      plugins: process.NODE_ENV === 'production' ? [vuexLocal()] : [logger(), vuexLocal()]
    });
    复制代码
  • 三、相似的第三方库session

相关文章
相关标签/搜索