• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

VUEX-action可以修改state吗

vue 搞代码 4年前 (2022-01-08) 46次浏览 已收录 0个评论

这篇文章主要介绍了VUEX-action可以修改state吗,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

首先回顾下vuex,官网图如下

  • Vuex 的 store 中的状态的唯一方法是提交 mutation(mutation类似于事件且必须是同步函数)
  • action 提交的是 mutation,而不是直接变更状态且可以包含任意异步操作(Action通过 store.dispatch 方法触发)

一幅图看清只能通过mutation修改state的原因

commit函数源码如下

 commit (_type, _payload, _options) { // check object-style commit const { type, payload, options } = unifyObjectStyle(_type, _payload, _options) const mutation = { type, payload } const entry = this._mutations[type] if (!entry) { if (process.env.NODE_ENV !== 'production') { console.error(`[vuex] unknown mutation type: ${type}`) } return } // 用来修改state this._withCommit(() => { entry.forEach(function commitIterator (handler) { handler(payload) }) }) this._subscribers.forEach(sub => sub(mutation, this.state)) if ( process.env.NODE_ENV !== 'production' && options && options.silent ) { console.warn( `[vuex] mutation type: ${type}. Silent option has been removed. ` + 'Use the filter functionality in the vue-devtools' ) } } 

this._withCommit来修改state,其源代码如下

 _withCommit (fn) { const committing = this._committing this._committing = true fn() this._committing = committing } 

其中_withCommit函数的参数fn是修改state的函数,在执行fn函数前,将this._committing置为true,理由是在源代码的251行resetStoreVM函数中判断严格模式的代码,如下:

 if (store.strict) { enableStrictMode(store) } 

当 vuex设置为严格模式, 执行enableStrictMode函数, 源码如下:

本文来源gaodai#ma#com搞*代#码9网#

 function enableStrictMode (store) { // $watch 函数来观察 state的变化 store._vm.$watch(function () { return this._data.$$state }, () => { // tate变化时,调用 assert函数 if (process.env.NODE_ENV !== 'production') { // 判断 store._committing assert(store._committing, `do not mutate vuex store state outside mutation handlers.`) } }, { deep: true, sync: true }) } 

当store._committing(this._committing)不为true,就会报出异常。
所以,当不是触发mutation来修改state, 就不会执行commit函数,也不会执行_withcommit函数,this._committing = true不会执行,当执行 enableStrictMode 时,会执行 assert 函数,这时store._committing为false,就会报出异常。

回归标题action可以修改state吗

不开启严格模式的情况下可以,但是不提倡。

综上所述,经测试得知可以修改并修改成功,但是严格模式下控制台会抛异常且action是异步的,不方便DevTool 调试

结语

我们开发要严格按照官方文档开发,避免不必要的错误产生。

以上就是VUEX-action可以修改state吗的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:VUEX-action可以修改state吗

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址