vuex _mutations[type] 为什么是以函数为元素的数组呢?

vuex _mutations[type] 为什么是以函数为元素的数组呢?

image.png

直接是一个函数不行吗?

阅读 2.1k
1 个回答

https://github.com/vuejs/vuex...

...
const entry = store._mutations[type] || (store._mutations[type] = [])
...

源码里这里初始化就是数组。

至于为什么,是因为 Vuex 里 Mutation 可能是重名的。试想假设存在这样的代码:

const store = new Vuex.Store({
    state: {},
    mutations: {
        ['foo/bar']() {}
    },
    modules: {
        foo: {
            namespaced: true,
            state: {},
            mutations: {
                bar () { }
            }
        }
    }
})
console.log(store._mutations);

你就会得到两个 Mutation Handler 了。

image.png

P.S. 其实我觉得这个设计不是很好,看着模块间“我隔离了、我装的.jpg”,但这个是借鉴了 Redux 的,Redux 就这样。等 Pinia 再成熟一些吧,就可以不用 Vuex 了。

推荐问题