简体   繁体   中英

Vuex state change propagation

I have a question about how Vuex reactivity is designed to work. 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.

// 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.

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

state: {
    databaseTables: []
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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