Vuex总结(二)

vuex的使用
1.组件中通过dispatch事件触发actions
    eg:
    methods: {
        事件名: function() {
          this.$store.dispatch("键值名", 需要存储的值);
        },
    }

2.通过actions进行commit提交给mutation
    eg:action.js
    键值名({commit},需要存储的值){
        commit(types.NEWSHOW,需要存储的值);
    },

3.mutation通过mutate给state
    eg:mutation.js
    [types.NEWSHOW](state,需要存储的值){
        state.需要存储的值的名称=需要存储的值;
    },

4.在store.js里进行getter处理
    eg:
    show(state){
      return state.需要存储的值的名称
    },

5.在组件里进行获取
    eg:
    import { mapGetters } from "vuex";
    computed: {
        ...mapGetters(["show"])
      },


6.注意:使用常量替代 Mutation 事件类型
    eg:mutation_type.js
    export const NEWSHOW="NEWSHOW"



eg:目录结构:
    store
        action.js
                    import * as types from './mutation_type'这是全局引入,也可以按需引入
                    export default{
                      newShow({commit},bData){
                        commit(types.NEWSHOW,bData);
                      }
                    }
        mutation.js
                    import * as types from './mutation_type'
                    export default{
                      [types.NEWSHOW](state,bData){
                        state.show=bData;
                      }
                    }
        mutation_type.js
                    export const NEWSHOW="NEWSHOW"
        store.js
                    import Vue from 'vue'
                    import Vuex from 'vuex'
                    import actions from './action'
                    import mutations from './mutation'
                    Vue.use(Vuex)

                    const store = new Vuex.Store({
                      state:{
                        show: false,
                      },
                      actions,
                      mutations,
                      getters:{
                        show(state){
                          console.log(state.show)
                          return state.show
                        }
                    })
                    export default store


至于事件触发和组件里获取和上面一样的!

转自博客:https://www.cnblogs.com/ldlx-mars/p/7833958.html

猜你喜欢

转载自blog.csdn.net/a3060858469/article/details/80717853
今日推荐