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

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

问题描述

在 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.

第一种方式

组件有一个绑定到父属性的 props 值:

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 :

所有 props 在子属性和父属性之间形成一种单向向下绑定:当父属性更新时,它会向下流到子属性,而不是相反.这可以防止子组件意外改变父组件的状态,从而使您应用的数据流更难理解.

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.

此外,每次更新父组件时,子组件中的所有 props 都会刷新为最新值.这意味着您不应该尝试改变子组件内的 prop.如果你这样做了,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

因此,为了从子组件更新 props,您应该使用 this.$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:使用 props 而不是引用父数据的原因?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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