This time I will show you how to implement communication between vue parent and child components, and what are theprecautions to implement communication between vue parent and child components. The following is a practical case, let's take a look.
Components are one of the most powerful features of vue.js, and the scopes of component instances are independent of each other, which means that data between different components cannot reference each other. Then how to communicate between components has become a key knowledge in Vue. This article will explain how to implement communication between parent and child components through the knowledge points of props, $ref and $emit. Before talking about how to implement communication, let's first build two components father.vue and child.vue as the basis of the example.//父组件
我是父组件!
//子组件我是子组件!
1. Communication through prop
The props option of the child component can receive data from the parent component. That's right, it can only be received. Props are one-way bound, that is, they can only be passed from the parent component to the child component, not the other way around. The delivery methods are also divided into two types:(1) Static delivery
The child component declares a custom attribute through the props option, and then the parent component You can pass data to subcomponents through this attribute when nesting tags.
我是父组件!
//通过自定义属性传递数据
{{message}}
(2) Dynamic transfer
We already know that we can pass a static value to props as above, but in more cases we need dynamic data. This can be achieved using v-bind. By binding custom properties of props through v-bind, what is passed is not a staticstring, it can be an expression, Boolean value, object, etc. any type of value.
我是父组件!
{{message}}
2. Implemented through $ref Communication
The official explanation for ref is: ref is used to register reference information for elements or subcomponents. Reference information will be registered on the $refs object of the parent component. Can’t understand, right? It's normal, I can't understand it either. How should that be understood? Take a look at my explanation:Properties and methodsdefined in.
我是父组件!
{{message}}
$ref 着重于索引,主要用来调用子组件里的属性和方法,其实并不擅长数据传递。而且ref用在dom元素的时候,能使到选择器的作用,这个功能比作为索引更常有用到。
3.通过$emit 实现通信
上面两种示例主要都是父组件向子组件通信,而通过$emit 实现子组件向父组件通信。
对于$emit官网上也是解释得很朦胧,我按我自己的理解是这样的:
vm.$emit( event, arg )
$emit 绑定一个自定义事件event,当这个这个语句被执行到的时候,就会将参数arg传递给父组件,父组件通过@event监听并接收参数。
{{title}}
我是子组件!
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
怎样使用nodejs express配置自签名https服务器
The above is the detailed content of How to implement communication between vue parent and child components. For more information, please follow other related articles on the PHP Chinese website!