One global data structure in Vue.js [duplicate]

2019-01-28 01:48发布

This question already has an answer here:

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?

1条回答
爷的心禁止访问
2楼-- · 2019-01-28 02:45

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.

查看更多
登录 后发表回答