Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One global data structure in Vue.js [duplicate]

I am building a single page app with Vue.js. It's a relatively simple app, more like an extended, opinionated spreadsheet. I'm using vue-router to handle different views of the app, some are used to enter new data, some are used to perform calculations on the data but all that data is intertwined (data entered in view #1 is used to enter data in view #2 and then both are used to calculate something in view #3).

That means I need a global data structure. From my research I found that I have several options to handle that:

  • the "proper" way: emitting events in components and handling them in the parent; that seems a little overcomplicated for what I want to achieve
  • accessing the parent scope directly in component templates via $parent.$data
  • my current solution, assigning the parent data reference to the child data object

Like so:

const REPORTS = {
  template: templates.reports,
  data: function(){
    return this.$parent.$data
  }
};

However, my sixth sense is telling me that it's not a good practice.

If I'm right, what are better ways of achieving this: one, global data structure, accessible from all components?

like image 880
ngr900 Avatar asked Nov 08 '22 04:11

ngr900


1 Answers

What you are looking for is a central state management as docs says:

Large applications can often grow in complexity, due to multiple pieces of state scattered across many components and the interactions between them. To solve this problem, Vue offers vuex: our own Elm-inspired state management library. It even integrates into vue-devtools, providing zero-setup access to time travel.

You can have a look at my other answers here and here

Vuex state can be read via getters, updated synchronously using mutations, updated asynchronously via actions from all the vue components and even divided into different modules.

like image 127
Saurabh Avatar answered Nov 15 '22 05:11

Saurabh