[Vuejs]-What is different between Vuex store and direct update data on $root?

3👍

I think you absolutely can rely on root state itself, but state management libraries helps to organize your code so many ways.

Due to using a single state tree, all states of your app are contained inside one big object.

As your app grows bigger and bigger this state tree gets really hard to handle.

For example, if you have one source of truth shared across multiple component like this:

var sourceOfTruth = {}

var vmA = new Vue({
  data: sourceOfTruth
})

var vmB = new Vue({
  data: sourceOfTruth
})

Works perfectly, but both components can mutate this state, so good luck debugging what and where went wrong if the state gets dirty somewhere. Any piece of data could be changed by any part of our app at any time, without leaving a trace.

This alone is a good reason to use a state management library, but vuex gives other useful tools too.

Just to mention a few: Vuex allows you to divide the store into modules. Each module can contain its own state, mutations, actions, getters, and even nested modules. If you want your modules to be more self-contained or reusable, you can mark it with namespaces as well.

I hope I could clarify a bit for you. State management rocks!

For details look at the docs:

https://v2.vuejs.org/v2/guide/state-management.html

https://vuex.vuejs.org/guide/modules.html

1👍

VueX (or Pinia a lightweight alternative) act as powerful state management storage, not only allowing you to access the data from anywhere in your application (like a database) but also tieing additional logic to process or chain other actions to the data you’re updating.

You can also organise your VueX store into multiple files to keep your codebase organised and ready to scale, meaning anyone jumping on to the project knows where to find globally accessible data.

Hope that helps inform your decision.

Leave a comment