Vue &vuex getter vs 通过 props 传递状态 [英] vue & vuex getter vs passing state via props

查看:27
本文介绍了Vue &vuex getter vs 通过 props 传递状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

推荐答案

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

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

那么你如何决定是通过props还是使用vuex呢?当我说使用 vuex 时,我的意思是直接从需要它的组件访问存储数据.诀窍是考虑每条数据与整个应用程序的关系.

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.

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

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.

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

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.

您可能对实例属性 $attrs

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

连同它的兄弟选项inheritAttrs.

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

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

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

这篇关于Vue &vuex getter vs 通过 props 传递状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆