[vue] vuex怎么知道state是通过mutation修改还是外部直接修改的?
Activity
wenyejie commentedon Jun 21, 2019
不知道哟, mark一下
logicool commentedon Jul 1, 2019
通过$watch监听mutation的commit函数中_committing是否为true
flyfox11 commentedon Jul 22, 2019
这道题感觉有点问题,在vuex严格模式下,是不让外部直接修改state的
WenJieLi1998 commentedon Apr 18, 2020
修改state数据,只有mutation这唯一路径
lt846786463 commentedon Oct 9, 2020
不通过mutation直接修改state浏览器会报错
Drikold commentedon Jul 25, 2021
默认严格模式下:Vuex 中修改 state 的唯一渠道就是执行 commit('xx', payload) 方法,其底层通过执行 this._withCommit(fn) 设置_committing 标志变量为 true,然后才能修改 state,修改完毕还需要还原_committing 变量。外部修改虽然能够直接修改 state,但是并没有修改_committing 标志位,所以只要 watch 一下 state,state change 时判断是否_committing 值为 true,即可判断修改的合法性。
跳转链接:Vuex 如何区分 State 是外部直接修改
rookiewp commentedon Mar 1, 2022
严格模式下:strict = true
vuex源码:
function enableStrictMode (store) {
watch(() => store._state.data, () => {
if (DEV) {
assert(store._committing,
do not mutate vuex store state outside mutation handlers.
)}
}, { deep: true, flush: 'sync' })
}