本文共 1958 字,大约阅读时间需要 6 分钟。
Components in Vue can communicate in various ways.
Vue中的组件可以通过多种方式进行通信。
The first way is using .
第一种方法是使用 。
Parents “pass down” data by adding arguments to the component declaration:
父级通过在组件声明中添加参数来“传递”数据:
Props are one-way: from parent to child. Any time the parent changes the prop, the new value is sent to the child and rerendered.
道具是单向的:从父母到孩子。 父母每次更改道具时,都会将新值发送给孩子并重新呈现。
The reverse is not true, and you should never mutate a prop inside the child component.
反之则不成立,您永远都不应在子组件内更改道具。
Events allow you to communicate from the children up to the parent:
通过事件,您可以从孩子到父母进行交流:
The parent can intercept this using the v-on
directive when including the component in its template:
当模板中包含组件时,父级可以使用v-on
指令截获此信息:
You can pass parameters of course:
您当然可以传递参数:
and retrieve them from the parent:
并从父级检索它们:
Using events you’re not limited to child-parent relationships.
使用事件,您不仅限于儿童与父母之间的关系。
You can use the so-called Event Bus.
您可以使用所谓的事件总线 。
Above we used this.$emit
to emit an event on the component instance.
上面我们使用了this.$emit
在组件实例上发出一个事件。
What we can do instead is to emit the event on a more generally accessible component.
相反,我们可以做的是在更易于访问的组件上发出事件。
this.$root
, the root component, is commonly used for this.
this.$root
是根组件,通常用于此目的。
You can also create a Vue component dedicated to this job, and import it where you need.
您也可以创建专用于此作业的Vue组件,然后将其导入所需的位置。
Any other component can listen for this event. You can do so in the mounted
callback:
任何其他组件都可以侦听此事件。 您可以在mounted
回调中执行此操作:
This is what Vue provides out of the box.
这就是Vue开箱即用的功能。
When you outgrow this, you can look into or other 3rd party libraries.
如果超出此限制,则可以查看或其他第三方库。
翻译自:
转载地址:http://zmqgb.baihongyu.com/