Vue:使用道具而不是引用父数据的原因? [英] Vue: Reasons to use props instead of referencing parent data?

查看:75
本文介绍了Vue:使用道具而不是引用父数据的原因?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在VueJS中,我已经看到了从组件访问父属性的不同方法。假设我想在我的组件中使用父属性 items

In VueJS, I have seen different ways of accessing parent properties from a component. Say I want to use the parent property items in my component.

第一种方式

该组件具有绑定到父属性的道具值:

The component has a props value bound to a parent property:

.js

Vue.component("example", {
  template: "<div></div>",
  props: ["myItems"]
});

.html

<example v-bind:my-items="items"></example>

第二种方式

子组件直接访问父项的属性,如下所示:

The child component accesses a parent's properties directly, like this:

this.$parent.items

问题

是否有有理由在第二种方法中使用更精细的第一种方法吗?是否存在复制这类数据的开销,而不是在需要时直接访问它?

Is there a reason to use the more elaborate first method over the second? Is there an overhead to "duplicating" data like that, vs. accessing it directly when needed?

推荐答案

props 应该在父组件中变异,根据官方文档

The props should be mutated in the parent component, according to the official doc :


所有道具形成了孩子之间的单向向下绑定属性和父级属性:当父属性更新时,它将向下流向子级,而不是相反。这可以防止子组件意外地改变父级状态,这可能会使您的应用程序的数据流更难理解。

All props form a one-way-down binding between the child property and the parent one: when the parent property updates, it will flow down to the child, but not the other way around. This prevents child components from accidentally mutating the parent’s state, which can make your app’s data flow harder to understand.

此外,每次更新父组件时,所有道具在子组件中将使用最新值进行刷新。 这意味着您不应该尝试改变子组件中的道具 。如果你这样做,Vue会在控制台中警告你

In addition, every time the parent component is updated, all props in the child component will be refreshed with the latest value. This means you should not attempt to mutate a prop inside a child component. If you do, Vue will warn you in the console

所以为了更新道具来自子组件你应该使用这个。$ emit 事件并发送新值以便处理父组件中的更新。

So in order to update props from child component you should use this.$emit event and send the new value in order to handle the update in the parent one.

这篇关于Vue:使用道具而不是引用父数据的原因?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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