fe-interview icon indicating copy to clipboard operation
fe-interview copied to clipboard

[vue] vuex怎么知道state是通过mutation修改还是外部直接修改的?

Open haizhilin2013 opened this issue 7 years ago • 7 comments

[vue] vuex怎么知道state是通过mutation修改还是外部直接修改的?

haizhilin2013 avatar Jun 20 '19 21:06 haizhilin2013

不知道哟, mark一下

wenyejie avatar Jun 21 '19 02:06 wenyejie

通过$watch监听mutation的commit函数中_committing是否为true

logicool avatar Jul 01 '19 01:07 logicool

这道题感觉有点问题,在vuex严格模式下,是不让外部直接修改state的

flyfox11 avatar Jul 22 '19 02:07 flyfox11

修改state数据,只有mutation这唯一路径

WenJieLi1998 avatar Apr 18 '20 07:04 WenJieLi1998

不通过mutation直接修改state浏览器会报错

lt846786463 avatar Oct 09 '20 06:10 lt846786463

默认严格模式下:Vuex 中修改 state 的唯一渠道就是执行 commit('xx', payload) 方法,其底层通过执行 this._withCommit(fn) 设置_committing 标志变量为 true,然后才能修改 state,修改完毕还需要还原_committing 变量。外部修改虽然能够直接修改 state,但是并没有修改_committing 标志位,所以只要 watch 一下 state,state change 时判断是否_committing 值为 true,即可判断修改的合法性。 跳转链接:Vuex 如何区分 State 是外部直接修改

Drikold avatar Jul 25 '21 23:07 Drikold

严格模式下: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' }) }

rookiewp avatar Mar 01 '22 01:03 rookiewp