简体   繁体   English

Vuex状态变化传播

[英]Vuex state change propagation

I have a question about how Vuex reactivity is designed to work. 我对Vuex反应性是如何工作的有疑问。 I have the following store: 我有以下商店:

// state
state: {
    database: {
        tables: []
    }
}

// mutator
ADD_TABLE(state, {table}) {
    state.database.tables.push(table);
}

So when the ADD_TABLE mutation happens vue components and the vuex watch react only when the object is directly changed and not reacting on nested property change. 因此,当发生ADD_TABLE突变时,vue组件和vuex监视仅在直接更改对象时起作用,而对嵌套属性更改不起作用。

// after the mutation happens
store.watch(state => state.database, change => console.log(change)) // this doesn't log
store.watch(state => state.database.tables, change => console.log(change)) // this does

Is this the desired behavior and why, or I have something breaking in my code? 这是所需的行为吗?为什么,或者我的代码有问题?

This is intended as a performance optimisation in Vue.js, similarly as PureComponents work in React for example. 这旨在作为Vue.js中的性能优化,类似于PureComponents在React中的工作。

By default only shallow comparison is done, meaning that only reference to the object property is checked. 默认情况下,仅进行浅表比较,这意味着仅检查对对象属性的引用。

Change will be picked up if database property is renamed, removed or another property is added to the object, indicating a change in the first level of the object. 如果将数据库属性重命名,删除或向该对象添加了另一个属性,则更改将被接受,这表明该对象的第一级发生了更改。

You can mitigate this by adding deep or optimising properties that you pass on. 您可以通过添加深层或优化传递的属性来减轻这种情况。

For example if your db object would only have a single child property, it could easily be changed to something like 例如,如果您的db对象只有一个子属性,则可以轻松地将其更改为类似

state: {
    databaseTables: []
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM