由于自己在日常开发中,使用vuex
时,直接在mutations
中定义方法,然后在.vue
中直接使用。但是目前发现有些人会在actions
中再定义一个方法进行调用。
目前actions
和mutations
只是存在同异步的区别。
code地址
const mutations = {
TOGGLE_SIDEBAR: state => {
state.sidebar.opened = !state.sidebar.opened
state.sidebar.withoutAnimation = false
if (state.sidebar.opened) {
Cookies.set('sidebarStatus', 1)
} else {
Cookies.set('sidebarStatus', 0)
}
},
CLOSE_SIDEBAR: (state, withoutAnimation) => {
Cookies.set('sidebarStatus', 0)
state.sidebar.opened = false
state.sidebar.withoutAnimation = withoutAnimation
},
TOGGLE_DEVICE: (state, device) => {
state.device = device
},
SET_SIZE: (state, size) => {
state.size = size
Cookies.set('size', size)
}
}
const actions = {
toggleSideBar({ commit }) {
commit('TOGGLE_SIDEBAR')
},
closeSideBar({ commit }, { withoutAnimation }) {
commit('CLOSE_SIDEBAR', withoutAnimation)
},
toggleDevice({ commit }, device) {
commit('TOGGLE_DEVICE', device)
},
setSize({ commit }, size) {
commit('SET_SIZE', size)
}
}
类似这段代码,其实actions
中,只是单纯调用了一下mutations
的方法,也没有做其他的操作。
目前github上比较火的vue
项目。
使用方式如上
直接使用
mutaions
的方法,无需在actions
再进行调用
分别采用不同的方式,这些有什么区别吗?
个人不太认同第一种方式,显得很累赘,特别是重度依赖vuex
时,相当于每次都要把mutaions
的方法在actions
再进行定义一遍。
还望各位道友解答一二
首先从Vuex文档中,你能了解到这两个的作用区别:
了解到上面两点,那是不是就一定的按照这种模式来呢?其实不然,我们同样可以在
Action中直接提交state
,同样可以在Mutation中有异步操作
,最后要的效果当然能达到预期,但是为什么就没有推荐这样做来?为什么一定要有这样的规定限制了?个人觉得,还是一个规范和解决副作用问题。就如文档中说的:
当然,以规范来编写代码,更助于团队的协作开发。