6

vuex为什么不能直接修改数据?

 1 year ago
source link: https://www.fly63.com/article/detial/12231
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

更新日期: 2022-11-04阅读: 507标签: vuex分享

扫一扫分享

我们知道在vueX中获取state数据可以通过this.$store.state.变量名进行获取,那么按常理来说,要想修改这个变量我们重新给他赋个值就行了。

下面的代码证明不通过mutation,而直接修改state修改确实生效了:

const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
}
}
})
console.log(store.state.count) //0
store.state.count = 3;
console.log(store.state.count) //3

其中,这样修改的话,store中的state数据可以改变且是响应式,浏览器控制台并无报错信息输出,但是不建议这样做。

官方不建议这么做是因为直接赋值的话我们VUEX无法对这个变量进行跟踪,无法得知state中的helloWorld变量在哪里被修改了,官方文档解释原因如下:

开启严格模式,仅需在创建 store 的时候传入 strict: true; 在严格模式下,无论何时发生了状态变更且不是由 mutation 函数引起的,将会抛出错误。这能保证所有的状态变更都能被调试工具跟踪到
throw error :    
[vuex] Do not mutate vuex store state outside mutation handlers

不经过mutations不能直接修改state中的数据,因为state是实时更新的,如果直接修改state中的数据是异步操作,当state异步还没有执行完,state的数据就有可能发生变化,会导致程序出问题,所以必须通过mutations限制state不允许异步操作。故更改Vuex 的store 中的状态的唯一方法是提交commit

链接: https://www.fly63.com/article/detial/12231


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK