[Vuejs]-How to change data in root component?

0đź‘Ť

This is ultimately where Vuex comes into the story for Vue.js. Vuex is a state management pattern/library that is based on the Flux/Redux architecture patterns if you have any familiarity with that:

Vuex is a state management pattern + library for Vue.js applications. It serves as a centralized store for all the components in an application, with rules ensuring that the state can only be mutated in a predictable fashion. It also integrates with Vue’s official devtools extension to provide advanced features such as zero-config time-travel debugging and state snapshot export / import.

The basic idea is that you have a centralized JavaScript object (the “store”), that holds all of the data for your application’s current state. Pieces of it can be added to, removed, or modified depending on the requirements of your app, synced with the server, etc. Components subscribe to the data they need from the central store using “getters”, but can also fire “actions” to “mutate” the central store as needed. The main point though is that everything travels in a singular direction. In your example above, the changes would fire as such:

  1. Text gets updated by user
  2. On blur (or click of save button, etc), Container.vue fires updateText action with the new text
  3. updateText Action calls mutation UPDATE_TEXT
  4. UPDATE_TEXT changes the store to hold the new value
  5. App.vue and Container.vue are using the mainText getter, which notices a change in the value and updates accordingly

[edit]
Also, one gotcha that can be a bit of a brain teaser when first getting to the Flux architecture patterns. “Actions” are where you perform any kind of AJAX-y goodness, this is why there is the distinction between actions and mutations. Actions take responsibility for interacting with the server (if needed) while Mutations are only concerned with the local state of the application. Even if your changes to the application state don’t need to interact with the server, you still push it through an Action -> Mutation cycle to maintain consistency throughout the app.

👤K3TH3R

Leave a comment