黄子涵

查漏补缺——说说Vuex的commit函数

问题

如题所示

答案

相关源码如下:

initComputeTime: ({commit}) => {
        commit('GET_RUNTIME_INTERVAL');
    },

vuex直接修改state 与 用commit提交mutation来修改state的差异

这里commit函数的作用是提交到mutation修改state,还有以下源码:

const mutations = {
    GET_RUNTIME_INTERVAL: (state) => {
        if (!timer || !state.runTimeInterval) {
            clearInterval(timer)
            timer = setInterval(() => {
                state.runTimeInterval = getTimeInterval(runAt);
            }, 1000);
        }
    }
}

在mutation属性里面有个GET_RUNTIME_INTERVAL函数,这个函数刚好是是commit函数的参数,当我们调用commit函数时,应该触发了mutation属性的这个GET_RUNTIME_INTERVAL函数,当GET_RUNTIME_INTERVAL函数被调用,它的参数,也就是state就会被函数里的内容而修改。

posted @ 2022-07-05 15:50  黄子涵  阅读(689)  评论(0编辑  收藏  举报