This question already has an answer here:
- Global data with VueJs 2 2 answers
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?
What you are looking for is a central state management as docs says:
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.