vuexモジュールのstate,getters,mutations,actions呼び出し

8674 ワード

モジュラー方式
  • は./srcディレクトリの下にstoreディレクトリを新規作成index.js[./src/store/index.js],./src/main.js中import,import store from './store'
  • import Vue from "vue";
    import Vuex from "vuex";
    
    import yqfk from "./yqfk";
    Vue.use(Vuex);
    const state = {};
    const mutations = {};
    const actions = {};
    export default new Vuex.Store({
      state,
      mutations,
      actions,
      modules: {
        yqfk
      }
    });
    
  • 上記storeディレクトリの下にyqfkを新規作成する.js[./src/store/yqfk.js],index.でエクスポート.jsでmodulesフィールドにインポートされた
  • const state = {
      test:1
    };
    const getters = {
    	testGetter(state){
    		return state.test
    	}
    }
    const mutations ={
    
    }
    const actions = {
    
    }
    export default {
      namespaced:true,
      state,
      getters,
      mutations,
      actions,
    }
    
  • vue単ページで
  • を使用
  • state:【this.$store.state.モジュール名.key】
  • getters:【this.$store.getters['モジュール名/key']]
  • mutations:【this.$store.commit('モジュール名/method’)】
  • actions:【this.$store.dispatch('モジュール名/method’)】
  • <script>
    export default {
      name: "Home",
      computed:{
        test(){
          return this.$store.state.yqfk.test
    	},
    	getTest(){
    		return this.$store.geters['yqfk/testGetter']
    	}
      }
    };
    </script>
    

    4.mapState,mapGetters,mapMutations,mapActions使用
    <script>
    import {mapState, mapGetters, mapMutations, mapActions} from 'vuex'
    
    export default {
      name: "Home",
      computed:{
      //        state    
      	...mapState({
      		test:state => state.yqfk.test
      	}),
     	...mapState('yqfk',{
     		test:state => state.test
     	}), 
       ...mapGetters('yqfk',{
       		getTest: 'testGetter'
       })
      }
    };
    </script>