vuex中state,getter,mutation,action,module的用法与理解

一.
State:{
count: 0
}
保存着所有的全局变量
组件中获取:

computed:{
    ...mapState({ //es6的对象展开运算符
        count: state => state.count //es6箭头函数
        'count' //如果名字与state中的名字一致,可这样简写
    })
}

二.
Getter: 对state中的数据派生出一些状态,例如对数据进行过滤。(可以认为是store中的计算属性),会对state中的变量进行过滤再保存,只要state中的变量发生了改变,它也会发生变化,不变化的时候,读的缓存。

getters: {
   doneTodos: state => {
      return state.todos.filter(todo => todo.done)
    },
    doneTodosCount: (state, getters) => { //Getter 也可以接受其他 getter 作为第二个参数:
    return getters.doneTodos.length
  }
 }

在组件中的用法(mapGetters 辅助函数):

 computed: {
  // 使用对象展开运算符将 getter 混入 computed 对象中
    ...mapGetters([
      'doneTodosCount', //如果想改名称,可以用对象的方式doneCount: 'doneTodosCount'
      'anotherGetter',
      // ...
    ])
  }

三.
Mutation:
更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。
一条重要的原则就是要记住 mutation 必须是同步函数。

mutations: {
  increment (state, n) {
    state.count += n
  }
}
 methods: {
    ...mapMutations([
      'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`

      // `mapMutations` 也支持载荷:
      'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)`
    ]),
    ...mapMutations({
      add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
    })
  }

四.
Action:
Action 类似于 mutation, 不同点在于,Action 提交的是 mutation,而不是直接变更状态。Action 可以包含任意异步操作,mutation只能是同步。
有点不同的是Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters。

 mutations: {
    increment (state) {
      state.count++
    }
  },
  actions: { //action 异步请求到数据后,用mutations中的方法传参到函数中,在函数中去改变state中的变量。
    increment (context) {
      context.commit('increment')
    }
  }

最后,如果我们利用 [async / await],我们可以如下组合 action:

actions: {
  async actionA ({ commit }) { //commit为触发mutations中的函数的方法,用到了es6的参数解构。
    commit('gotData', await getData())  
  },
  async actionB ({ dispatch, commit }) {
    await dispatch('actionA') // 等待 actionA 完成  actions中的方法通过dispatch()触发
    commit('gotOtherData', await getOtherData())
  }
}

五.
Module: // 如下类似这样的模块,可以写很多,最后都引入到一个文件。分散管理。

import * as types from '../mutations-type' //变更为常量名,有利于项目的理解。如:export const SOME_MUTATION = 'someMutation'

const state = {
    responseData: '', // 响应数据
    memoryKey: '' //内存地址的id
}

// getters
const getters = {
    msgShow: state => state.msgShow,
    noDataShow: state => state.noDataShow
}

// actions
const actions = {
    getDetailData(context, payload) {
        EMAjax.get({
            url: payload.url,
            data: payload.data,
            beforeSend: function() {
                state.responseData = ''; // 数据请求前先初始化
            },
            success: function(response) {
            },
            error: function(err) {} {
        })
    },
    // 调用终端方法 将数据保存到终端内存中 并返回内存地址的id 有返回值 返回值int 
    terminalSaveString(context, payLoad) {
        context.commit(types.TERMINAL_SAVE_STRING, payLoad);
    },
}

// mutations
const mutations = {
    [types.GET_DETAIL_DATA](state, { data }) { 
        if (data.records.length > 0) {
            state.responseData = data;
        } else {
            state.isShowMsg = true;
        }
    },
    // 调用终端方法 将数据保存到终端内存中 并返回内存地址的id 有返回值 返回值int 
    [types.TERMINAL_SAVE_STRING](context, payLoad) {
        state.memoryKey = EMTerminal.terminalInsertMemory(payLoad);
    },
}

export default {
    namespaced: true,   //namespaced: true 的方式使其成为带命名空间的模块。保证在变量名一样的时候,添加一个父级名拼接。
    state,
    getters,
    actions,
    mutations
}

生成实例的时候 都放在Store的modules中
export default new Vuex.Store({
modules: {
globalInputBox,
globalMenu,
searchDetail,
searchDetailAll,
searchDetailQuota,
searchDetailBlocks,
searchDetailFunction,
searchDetailSecurity,
searchDetailSpecial,
searchDetailNews,
searchDetailNotice,
searchDetailReports,
searchDetailLaws
}
});

发布了54 篇原创文章 · 获赞 42 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/qq_42043377/article/details/100762725