vue & vuex getter vs 通过 props 传递状态

vue & vuex getter vs passing state via props

我看到很多人建议通过 props 将状态传递给组件,而不是直接在组件内部访问 vue 状态,以使其更易于重用。

但是,如果我始终如一地这样做,这将意味着只有路由根组件会与商店通信,并且所有数据都需要通过嵌套层次结构传递才能获得最终组件。这样好像很容易造成混乱:

Dashboard
   Profile
   Billing
      History
      CreditCards
         CreditCard

如何加载用户信用卡的数据?在 Dashboard 中并将其一直传递到树下?

每个组件,无论其层次结构位置如何,都可以与商店通信。

在每个组件中,您可以访问对象 this.$store,因此您可以调度 actions、通过 mutations 提交数据或通过 getters[=17= 读取数据]

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
    }
  }
}

会造成混乱,你是对的。这是 vuex 解决的问题之一。

那么怎么决定是传props还是用vuex呢?当我说使用 vuex 时,我的意思是直接从需要它的组件访问商店数据。诀窍是考虑每条数据与整个应用程序的关系。

在整个页面、许多 DOM 层次结构、不同页面等中重复使用的数据是使用 vuex 的理想情况。

另一方面,一些组件耦合得如此紧密,传递 props 是显而易见的解决方案。例如,您有一个 list-container 组件,它的直接子组件是 list 组件,并且它们都需要相同的列表数据。在这种情况下,我会将列表数据作为道具传递给 list 组件。


您可能对实例感兴趣属性$attrs

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

连同它的兄弟选项 inheritAttrs

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

结合使用这 2 个,您可以使用更少的样板代码将 props 传递到多个组件级别。