设计模式(4): 给组件实现单独的store

概述

最近最近作项目的时候总会思考一些大的应用设计模式相关的问题,我把本身的思考记录下来,供之后开发时参考,相信对其余人也有用。vue

组件自身的store

咱们在开发组件的时候,时常都有这种需求,就是但愿给组件一个独立的store,这个store可能被用来储存数据,共享数据,还能够被用来对数据作一些处理,抽离核心代码等。vuex

store的数据不共享

若是组件自身的store是每一个实例独自拥有的而且不共享的话,咱们能够直接用一个类来实现。设计模式

// store.js
export default class Store {
  constructor(data, config) {
    this.config = config;
    this.init(data);
  }

  init(data) {
    // 对数据作处理
  }

  // 其它方法
}

而后咱们在组件中实例化这个store,而后挂载到data属性里面去:this

<script>
import Store from './store';

export default {
  data() {
    return {
      store: [],
    };
  },
  methods: {
    initStore() {
      // 生成 options 和 config
      this.store = new Store(options, config);
    },
  },
};
</script>

store的数据须要共享

若是store的数据须要共享,咱们建议用动态挂载vuex的store的方法,示例以下:设计

// store.js
const state = {
  data: [],
};

const getters = {};

const actions = {};

const mutations = {
  setData(state, value) {
    this.state.data = [...value];
  },
};

export default {
  state,
  getters,
  actions,
  mutations,
};

而后咱们在注册这个组件的时候动态挂载这个store:code

import Store from './store';

export default {
  install(Vue, options) {
    Vue.store.registerModule('xxx', store);
  },
};

最后咱们就能够在组件中使用这个store的数据啦~~~ip

相关文章
相关标签/搜索