博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Vue.js组件通信
阅读量:2503 次
发布时间:2019-05-11

本文共 1958 字,大约阅读时间需要 6 分钟。



Components in Vue can communicate in various ways.

Vue中的组件可以通过多种方式进行通信。

道具 (Props)

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.

反之则不成立,您永远都不应在子组件内更改道具。

使用事件从孩子与父母沟通 (Using Events to communicate from children to parent)

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 an Event Bus to communicate between any component)

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回调中执行此操作:

备择方案 (Alternatives)

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/

你可能感兴趣的文章
ES6学习之字符串的扩展
查看>>
[SDOI2014]旅行
查看>>
scala学习笔记-Actor(19)
查看>>
ADT+NDK+OpenCV 环境部署
查看>>
GDB调试实用命令
查看>>
Java 浮点运算
查看>>
线程安全
查看>>
Centos7安装tomcat8
查看>>
MySQL基本命令和常用数据库对象
查看>>
poj 1222 EXTENDED LIGHTS OUT(位运算+枚举)
查看>>
秘密:之所以不搞军事同盟,俄罗斯
查看>>
µC/OS-II版本升级指南
查看>>
hibernate中持久化对象的生命周期(三态:自由态,持久态,游离态 之间的转换)...
查看>>
postgres出现Server doesn't listen错误解决办法
查看>>
linux shell学习--awk练习
查看>>
敏捷开发一千零一问系列之十二:敏捷实施的步骤?
查看>>
TCP三次握手机制中的seq和ack
查看>>
java内部类的定义原则
查看>>
2017年11月26日 C#流&&窗体对话框
查看>>
endl与\n的区别
查看>>