vue & vuex getter vs passing state via props

故事扮演 提交于 2020-01-01 04:07:07

问题


I have seen many people advising to pass state to components via props rather than accessing the vue state directly inside the component in order to make it more reusable.

However, if I do this consistently this would mean that only the routes root component would communicate with the store and all data needs to be passed through the nested hierarchy in order to get the final component. This seems like it would easily cause a mess:

Dashboard
   Profile
   Billing
      History
      CreditCards
         CreditCard

How would I load data for a users creditcard? In Dashboard and pass it all the way down the tree?


回答1:


It will cause a mess, you are correct. This is one of the problems that vuex solves.

So how do you decide whether to pass props or use vuex? When i say use vuex, i mean to access the store data directly from the component that needs it. The trick is to consider each piece of data's relationship to the overall application.

Data that is used repeatedly throughout the page, down many DOM hierarchies, in different pages, etc, is the ideal case in which to use vuex.

On the other hand, some components are so tightly coupled that passing props is the obvious solution. For example, you have a list-container component, whose direct child is the list component, and both of them need the same list data. In this situation, i would pass the list data down to the list component as a prop.


You may be interested in the instance property $attrs

https://vuejs.org/v2/api/#vm-attrs

along with it's sibling option inheritAttrs.

https://vuejs.org/v2/api/#inheritAttrs

Using these 2 in combination allows you to pass props down multiple component levels with less boilerplate code.




回答2:


Every Component, regardless of their Hierarchy position, can communicate with the store.

Inside every Component, you have access the object this.$store so you can dispatch actions, commit data through mutations or read data via getters

Read the documentation for further details:

By providing the store option to the root instance, the store will be injected into all child components of the root and will be available on them as this.$store.

const Counter = {
  template: `<div>{{ count }}</div>`,
  computed: {
    count () {
      return this.$store.state.count
    }
  }
}


来源:https://stackoverflow.com/questions/47069902/vue-vuex-getter-vs-passing-state-via-props

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!