在 vue.js 中有哪些替代方法可以将数据传递给 child 组件而不是 props

What are some alternatives in vue.js to passing data to child components other than props

我知道传递数据的正确模式 from/to vue.js 中的 parent/child 组件是将道具从 parent 传递到 child 并且发出从 child 到 parent 的事件。但是这样有什么问题吗:

this.$refs['child-component'].setValue(val)

有人告诉我应该谨慎地使用 refs 来访问 child 组件,并且只有在没有其他方法时才使用。

如果我想更新未绑定到 prop 的 child 组件中数组中字段的值怎么办,如下所示:

this.$refs['child-component'].childArray[index] = val;

...其中 childArray 不是 child-component 的道具?我需要制作 childArray child-component 的道具吗?但随后 parent 有责任维护 child 数组。如果维护 child 数组不是 parent 组件的业务怎么办?

谢谢。

其实,乱动child的内部数据根本不是parent的事情。你不应该直接改变 child 的内部数据 - 相反,考虑调用一个方法或发出一个事件(应该由 child 处理)。

目前您正在 parent 和 child 之间创建紧密耦合 - 现在 parent 因 child 内部知识而超载。明天,当您决定更改 child 的实现时(无论出于何种原因)- 很可能您还必须检查所有 parents,其中使用此 child 只是为了检查您的更改没有打破那些 parent 的假设。