vuexの原則

vuex実装:

  1. VUEプロジェクトでvuexインストールします
  2. プラグイン機構、Vue.use(vuex)の使用は、通話の方法vuexをインストールし、ローディングvuexの使用のVUE
  3. beforeCreateフック関数混在グローバルに注入店の前にミックスインのメカニズムのVueの混合使用、および各コンポーネントのインスタンスを聞かせて、国家間のコンポーネントの共有を実現するために、$ストアにアクセスすることができます

VueXソースは以下に示し:
ここに画像を挿入説明

サンプルコード:
main.js

import Vue from 'vue'
import App from './App.vue'
import store from './store'

Vue.config.productionTip = false

new Vue({
  store,
  render: h => h(App),
}).$mount('#app')

store.js

import Vue from 'vue'

import Vuex, {Store} from './vuex'

Vue.use(Vuex);

const state = {
  count: 10,
  val: 2
}

const getters = {
  result(state, getters){
    return state.count * state.val;
  },
  result2(state, getters){
    return state.count / state.val;
  }
}

const mutations = {
  modify(state, value){
    state.count = value;
  }

}

const actions = {
  requestModifyCount(context, value){
    setTimeout(() => {
      context.commit('modify', value);
    }, 2000);
  }

}
// const store = new Vuex.Store({
const store = new Store({
  state,
  getters,
  mutations,
  actions
});

export default store;

vuexファイルの下でindex.js

let Vue = null;

export default class Vuex{
  static install(_Vue){

    Vue = _Vue;

    // 混入,为了每一个组件和实例,都能访问到$store,前提是根实例配置了store
    Vue.mixin({
      beforeCreate(){
        if(this.$root.$options.store){
          this.$store = this.$root.$options.store;
        }
      }
    })
    
  }
}

export class Store{

  constructor({state, getters, mutations, actions}){
    this._state = state;
    this._getters = getters;
    this._mutations = mutations;
    this._actions = actions;

    // 转换实例将要使用的计算属性
    let obj = {};
    Object.entries(getters).forEach(([key, value])=>{
      obj[key] = ()=>{
        return value(state, obj);
      }
    })

    // 构建实例
    this._vm = new Vue({
      data: state,
      computed: obj
    });

    // 处理data,转为store.state
    this.state = this._vm.$data;

    // 构建getters
    this._handleGetters();  
    
  }

  _handleGetters(){
    //$store._vm.result    $store.getters.result
    this.getters = {};
    Object.keys(this._getters).forEach(key=>{
      
      Object.defineProperty(this.getters, key, {
        enumerable: true,
        configurable: true,
        get: ()=>{
          return this._vm[key];
        }
      });
    })
  }


  commit(name, payload){
    //调用插件,提醒开发者数据的变化流程
    this._mutations[name](this.state, payload);
  }


  dispatch(name, payload){
    // 使用promise做封装
    this._actions[name](this, payload);
  }
  
}

Vuex.Store = Store;

Vuexシナリオ:

  1. 同じ状態に依存して複数のビュー
  2. 同じ状態のニーズの異なるビューからの動作が変更されます
公開された15元の記事 ウォン称賛24 ビュー481

おすすめ

転載: blog.csdn.net/weixin_44691775/article/details/104425529