vuex学習

17441 ワード

vuex学習
概要
  • Vuexの状態記憶は応答式である.Vueコンポーネントがstoreから状態を読み出すとき、storeの状態が変化すると、対応するコンポーネントも効率的に更新される
  • .
  • storeの状態を直接変えることはできません.storeのステータスを変更する唯一の方法は、明示的にmutationをコミットすることです.これにより、各状態の変化を容易に追跡することができ、アプリケーション
  • をよりよく理解するためのツールを実現することができます.
  • storeのステータスは応答式であるため、コンポーネントでstoreを呼び出すステータスは、計算プロパティで返すだけで簡単です.トリガ変化は、コンポーネントのmethodsにmutation
  • をコミットするだけである.
  • 注意:Vuexを使用すると、すべての状態をVuexに入れる必要はありません.すべてのステータスをVuexに配置すると、ステータスの変化がより明示的でデバッグしやすくなりますが、コードが冗長で直感的ではありません.一部のステータスが単一のコンポーネントに厳密に属している場合は、コンポーネントのローカルステータスとして使用することが望ましい.アプリケーション開発の必要性に基づいて、
  • を比較し、確定する必要があります.
    コアState:単一ステータスツリー
    コンポーネント取得ステータス
    const app = new Vue({
      el: '#app',
      //   store       “store”   ,     store            
      store,
      components: { Counter },
      template: `
        
    class="app"> <counter>counter> div> ` }); const Counter = { template: `<div>{{ count }}div>`, computed: { count() { // store , store , this.$store return this.$store.state.count; } } };

    mapState : state

    • 。 , mapState
    • mapState , computed mapState
    • state , mapState
    import { mapState } from 'vuex';
    //      mapState            computed
    export default {
      computed: mapState({
        //     ,             
        count: state => state.count,
        //        ,    state => state.count
        countAlias: 'count'
      })
    };
    //            
    export default {
      computed: {
        localCount: () => {},
        //          
        ...mapState({
          count: state => state.count,
          countAlias: 'count'
        })
      }
    };
    Getter:storeの とみなすことができる
  • stateによっていくつかの を させる があり、これらの の くのコンポーネントが される 、 コンポーネントが する を くか、 の に するのは ではありません.この はGetter
  • まで する がある.
  • Vuexを すると、storeでgetterを できます(storeの プロパティと えられます). プロパティと に、getterの り は、その に づいてキャッシュされ、その が された にのみ されます.
    const store = new Vuex.Store({
      state: {
        todos: [{ id: 1, text: '...', done: true }, { id: 2, text: '...', done: false }]
      },
      getters: {
        //           state
        doneTodos: state => {
          return state.todos.filter(todo => todo.done);
        },
        //           getters
        doneTodosCount: (state, getters) => {
          return getters.doneTodos.length;
        },
        //       
        getTodoById: state => id => {
          return state.todos.find(todo => todo.id === id);
        }
      }
    });
    const Counter = {
      computed: {
        doneTodos() {
          return this.$store.getters.doneTodos;
        },
        doneTodosCount() {
          return this.$store.getters.doneTodosCount;
        },
        getTodoById(id) {
          return this.$store.getters.getTodoById(id);
        }
      }
    };

    mapGetters:storeのgetterをローカル プロパティにマッピングする
    const Counter = {
      computed: {
        //     
        ...mapGetters(['doneTodos', 'doneTodosCount', 'getTodoById']),
        //            
        ...mapGetters({
          _doneTodos: 'doneTodos'
        })
      }
    };
    Mutation:stateの を する
  • Vuexのstoreの を する の は、Mutation
  • をコミットすることです.
  • Mutationコールバック の のパラメータはstateであり、2 のパラメータは パラメータ-コミット (Payload)
  • である.
  • は、ES 6+の を するMutationイベントタイプの わりに を することができる. の はあなた です. の の が な なプロジェクトでは、これが ちます.しかし、もしあなたが きでないなら、あなたは にこのようにしないことができます
  • Mutationは、
  • である があります.
  • mapMutations は、 の2つと しており、
  • ではなく な にマッピングする がある.
    import Vuex from 'vuex';
    import { SOME_MUTATION } from './mutation-types';
    
    const store = new Vuex.Store({
      state: {
        count: 1
      },
      mutations: {
        increment(state, n) {
          state.count += n;
        },
        //   mutation-types     SOME_MUTATION === 'increment'
        [SOME_MUTATION](state, n) {
          state.count += n;
        }
      }
    });
    
    //   
    store.commit('increment', 10);
    //   
    store.commit({
      type: 'increment',
      amount: 10
    });
    //    mapMutations
    const store = {
      methods: {
        ...mapMutations([
          //   `this.increment()`     `this.$store.commit('increment')`
          'increment'
        ]),
        ...mapMutations({
          add: 'increment'
        })
      }
    };
    this.increment(10); //   
    Action
  • Actionはmutation
  • に する.
  • Actionは、ステータス
  • を するのではなく、mutationをコミットする.
  • アクションは、 の
  • を むことができる.
  • Action はstoreインスタンスと じメソッドと を つcontextオブジェクトを け れるのでcontextを び すことができます.commitはmutationをコミットするかcontextを する.stateとcontext.gettersはstateとgetters
  • を する
  • ES 6+のパラメータを して、コード
  • を する
    const store = new Vuex.Store({
      state: {
        count: 1
      },
      mutations: {
        increment(state, n) {
          state.count += n;
        }
      },
      actions: {
        //    ES6+           
        increment({ commit }, data) {
          //     
          setTimeout(() => {
            commit('increment', data);
          }, 2000);
        }
      }
    });
    
    //   
    store.dispatch('increment', 10);
    //   
    store.dispatch({
      type: 'increment',
      amount: 10
    });
    //    mapMutations
    const store = {
      methods: {
        ...mapActions([
          //   `this.increment()`     `this.$store.dispatch('increment')`
          'increment'
        ]),
        ...mapActions({
          add: 'increment'
        })
      }
    };
    this.increment(10); //   
    
    // Action       ,         Promise       Action
    const store = new Vuex.Store({
      state: {
        count: 1
      },
      mutations: {
        increment(state, n) {
          state.count += n;
        }
      },
      actions: {
        increment({ commit }, data) {
          new Promise((resove, reject) => {
            setTimeout(() => {
              commit('increment', data);
              resove();
            }, 2000);
          });
        }
      }
    });
    store.dispatch('increment', 10).then(() => {
      console.log('    ');
    });
    
    //         async / await
    const store = new Vuex.Store({
      actions: {
        actions: {
          async actionA({ commit }) {
            commit('gotData', await getData());
          },
          async actionB({ dispatch, commit }) {
            await dispatch('actionA'); //    actionA   
            commit('gotOtherData', await getOtherData());
          }
        }
      }
    });
    Module:storeモジュール
  • Vuexではstoreをモジュールに できます. モジュールは、 のstate、mutation、action、getter、さらにはネストされたサブモジュール
  • を する.
  • モジュール のmutationおよびgetterについて、 1のパラメータは、モジュールの オブジェクト
  • である.
  • モジュール のactionは、 がcontextを する.stateが する、ルートノードの はcontextである.rootState. じようにcontextもあります.rootGetter
  • モジュール のgetterでは、ルートノードの が3 のパラメータとして
  • に する.
    const moduleA = {
      state: { count: 0 },
      mutations: {
        increment(state) {
          //     `state`           
          state.count++;
        }
      },
      getters: {
        doubleCount(state) {
          return state.count * 2;
        }
      },
      actions: {
        // rootState      
        incrementIfOddOnRootSum({ state, commit, rootState }) {
          if ((state.count + rootState.count) % 2 === 1) {
            commit('increment');
          }
        }
      }
    };
    const moduleB = {
      state: { count: 0 }
    };
    
    const store = new Vuex.Store({
      modules: {
        a: moduleA,
        b: moduleB
      }
    });
    
    store.state.a; // moduleA    
    store.state.b; // moduleB    

    ネーミングスペース:モジュールをよりよくカプセル
  • のデフォルトでは、モジュール のaction、mutation、getterはグローバルネーミングスペースに されている.これにより、 のモジュールが じmutationまたはactionに できるようにする
  • .
  • namespaced:trueを することによりネーミングスペース きモジュール
  • とする.
  • namespacedプロパティを した 、モジュール のコード
  • を する はありません.
  • ネーミングスペースが なgetterとactionは、 されたgetter、dispatch、commit
  • を します.
  • モジュールが すると、そのすべてのgetter、action、mutationは、モジュール の に づいて
  • と に を する.
  • グローバルstateとgetterを する は、rootStaterootGetterが 3および 4のパラメータとしてgetterに され、contextオブジェクトのプロパティによってaction
  • に されます.
  • グローバルネーミングスペース でactionを またはmutationをコミットする がある 、{ root: true }を 3のパラメータとしてdispatchまたはcommit
  • に す.
  • store.registerModule モジュール
  • store.unregisterModuleモジュールをアンインストールします.この では、 モジュール(storeの に されたモジュール)
  • をアンインストールできません.
    const store = new Vuex.Store({
      modules: {
        account: {
          namespaced: true,
          state: {},
          getters: {
            isAdmin() {} // getters['account/isAdmin']
          },
          actions: {
            login() {} // dispatch('account/login')
          },
          mutations: {
            login() {} // commit('account/login')
          },
          modules: {
            myPage: {
              state: {},
              getters: {
                profile() {} // getters['account/profile']
              }
            },
            posts: {
              namespaced: true,
              state: {},
              getters: {
                popular() {} // getters['account/posts/popular']
              }
            }
          }
        }
      }
    });
    
    //   
    const store = new Vuex.Store({
      modules: {
        foo: {
          namespaced: true,
          getters: {
            someGetter(state, getters, rootState, rootGetters) {
              getters.someOtherGetter; // 'foo/someOtherGetter'
              rootGetters.someOtherGetter; // 'someOtherGetter'
            }
          },
          actions: {
            someAction({ dispatch, commit, getters, rootGetters }) {
              getters.someGetter; // 'foo/someGetter'
              rootGetters.someGetter; // 'someGetter'
              dispatch('someOtherAction'); // 'foo/someOtherAction'
              dispatch('someOtherAction', null, { root: true }); // 'someOtherAction'
              commit('someMutation'); // 'foo/someMutation'
              commit('someMutation', null, { root: true }); // 'someMutation'
            }
          }
        }
      }
    });
    
    //     
    //    :
    import { mapState } from 'vuex';
    export default {
      computed: {
        ...mapState({
          a: state => state.some.nested.module.a,
          b: state => state.some.nested.module.b
        })
      },
      methods: {
        ...mapActions(['some/nested/module/foo', 'some/nested/module/bar'])
      }
    };
    //    :
    import { mapState } from 'vuex';
    export default {
      computed: {
        ...mapState('some/nested/module', {
          a: state => state.a,
          b: state => state.b
        })
      },
      methods: {
        ...mapActions('some/nested/module', ['foo', 'bar'])
      }
    };
    //    :
    import { createNamespacedHelpers } from 'vuex';
    const { mapState, mapActions } = createNamespacedHelpers('some/nested/module');
    export default {
      computed: {
        ...mapState({
          a: state => state.a,
          b: state => state.b
        })
      },
      methods: {
        ...mapActions(['foo', 'bar'])
      }
    };
    
    //       
    //      `myModule`
    store.registerModule('myModule', {});
    //        `nested/myModule`
    store.registerModule(['nested', 'myModule'], {});