vue & vuex getter vs passing state via props

╄→гoц情女王★ 提交于 2019-12-03 10:40:42

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.

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