网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

VUEX-action能否修改state-创新互联

这篇文章给大家分享的是有关VUEX-action能否修改state的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

成都创新互联公司是专业的高安网站建设公司,高安接单;提供网站建设、做网站,网页设计,网站设计,建网站,PHP网站建设等专业做网站服务;采用PHP框架,可快速的进行高安网站开发网页制作和功能扩展;专业做搜索引擎喜爱的网站,专业的做网站团队,希望更多企业前来合作!

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

VUEX-action能否修改state

  • Vuex 的 store 中的状态的唯一方法是提交 mutation(mutation类似于事件且必须是同步函数)

  • action 提交的是 mutation,而不是直接变更状态且可以包含任意异步操作(Action通过 store.dispatch 方法触发)

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

VUEX-action能否修改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函数, 源码如下:

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”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!


新闻标题:VUEX-action能否修改state-创新互联
标题网址:http://bjjierui.cn/article/hhehs.html

其他资讯