Home Web Front-end JS Tutorial How to implement communication between vue parent and child components

How to implement communication between vue parent and child components

May 28, 2018 am 11:27 AM
components communication

This time I will show you how to implement communication between vue parent and child components, and what are the precautions 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.

//父组件
<template>
 <p>
  <h1>我是父组件!</h1>
  <child></child>
 </p>
</template>
<script>
import Child from '../components/child.vue'
export default {
 components: {Child},
}
</script>
Copy after login
//子组件
<template>
 <h3>我是子组件!</h3>
</template>
<script>
</script>
Copy after login
The codes in these two parts are very clear. The parent component imports the child component through import and registers it in the components attribute. Then the child component can be embedded in the parent using the tag Components. The effect after running father.vue is as follows:

Example effect one

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.

 <!-- 父组件 -->
<template>
 <p>
  <h1>我是父组件!</h1>
  <child message="我是子组件一!"></child> //通过自定义属性传递数据
 </p>
</template>
<script>
import Child from '../components/child.vue'
export default {
 components: {Child},
}
</script>
Copy after login
 <!-- 子组件 -->
<template>
 <h3>{{message}}</h3>
</template>
<script>
 export default {
  props: ['message']  //声明一个自定义的属性
 }
</script>
Copy after login

(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 static

string, it can be an expression, Boolean value, object, etc. any type of value.

 <!-- 父组件 -->
<template>
 <p>
  <h1>我是父组件!</h1>
  <child message="我是子组件一!"></child>
  <!-- 这是一个 JavaScript 表达式而不是一个字符串。-->
  <child v-bind:message="a+b"></child>
  <!-- 用一个变量进行动态赋值。-->
  <child v-bind:message="msg"></child>
 </p>
</template>
<script>
import Child from '../components/child.vue'
export default {
 components: {Child},
 data() {
  return {
   a:'我是子组件二!',
   b:112233,
   msg: '我是子组件三!'+ Math.random()
  }
 }
}
</script>
Copy after login
 <!-- 子组件 -->
<template>
 <h3>{{message}}</h3>
</template>
<script>
 export default {
  props: ['message']
 }
</script>
Copy after login
The effect is like this:

Example effect two

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:

  1. If ref is used on a subcomponent, it points to the component instance, which can be understood as the index of the subcomponent. It is possible to obtain the subcomponent through $ref.

    Properties and methods defined in.

  2. If ref is used on an ordinary DOM element, the reference points to the DOM element. Through $ref, it is possible to obtain the attribute collection of the DOM and easily access the DOM element. The function is the same as JQ Selectors are similar.

How to achieve communication through $ref? Next, I will implement the function implemented by the above prop using $ref:

<!-- 父组件 -->
<template>
 <p>
  <h1>我是父组件!</h1>
  <child ref="msg"></child>
 </p>
</template>
<script>
 import Child from '../components/child.vue'
 export default {
  components: {Child},
  mounted: function () {
   console.log( this.$refs.msg);
   this.$refs.msg.getMessage('我是子组件一!')
  }
 }
</script>
Copy after login
 <!-- 子组件 -->
<template>
 <h3>{{message}}</h3>
</template>
<script>
 export default {
  data(){
   return{
    message:''
   }
  },
  methods:{
   getMessage(m){
    this.message=m;
   }
  }
 }
</script>
Copy after login
From the above code, we can find that through ref='msg', the instance of the subcomponent child can be pointed to $ref, and through .msg.getMessage() calls the getMessage method of the subcomponent and passes the parameters to the subcomponent. The following is the content printed by "console.log( this.$refs.msg);", which can give everyone a better understanding of what we get through ref:

console.log

The final effect is like this:

Example effect three

One more thing to add here is that prop and $ The difference between ref:

  1. prop focuses on the transfer of data, it cannot call properties and methods in subcomponents. For usage scenarios such as customizing the title and content when creating an article component, prop is most suitable for use.

  2. $ref 着重于索引,主要用来调用子组件里的属性和方法,其实并不擅长数据传递。而且ref用在dom元素的时候,能使到选择器的作用,这个功能比作为索引更常有用到。

3.通过$emit 实现通信

上面两种示例主要都是父组件向子组件通信,而通过$emit 实现子组件向父组件通信。

对于$emit官网上也是解释得很朦胧,我按我自己的理解是这样的:

vm.$emit( event, arg )
Copy after login

$emit 绑定一个自定义事件event,当这个这个语句被执行到的时候,就会将参数arg传递给父组件,父组件通过@event监听并接收参数。

<template>
 <p>
  <h1>{{title}}</h1>
  <child @getMessage="showMsg"></child>
 </p>
</template>
<script>
 import Child from '../components/child.vue'
 export default {
  components: {Child},
  data(){
   return{
    title:''
   }
  },
  methods:{
   showMsg(title){
    this.title=title;
   }
 }
 }
</script>
Copy after login
<template>
 <h3>我是子组件!</h3>
</template>
<script>
 export default {
  mounted: function () {
   this.$emit('getMessage', '我是父组件!')
  }
 }
</script>
Copy after login

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

怎样使用nodejs express配置自签名https服务器

怎样用mpvue构建小程序

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1657
14
PHP Tutorial
1257
29
C# Tutorial
1230
24
New generation of optical fiber broadband technology - 50G PON New generation of optical fiber broadband technology - 50G PON Apr 20, 2024 pm 09:22 PM

In the previous article (link), Xiao Zaojun introduced the development history of broadband technology from ISDN, xDSL to 10GPON. Today, let’s talk about the upcoming new generation of optical fiber broadband technology-50GPON. █F5G and F5G-A Before introducing 50GPON, let’s talk about F5G and F5G-A. In February 2020, ETSI (European Telecommunications Standards Institute) promoted a fixed communication network technology system based on 10GPON+FTTR, Wi-Fi6, 200G optical transmission/aggregation, OXC and other technologies, and named it F5G. That is, the fifth generation fixed network communication technology (The5thgenerationFixednetworks). F5G is a fixed network

How to install the Windows 10 old version component DirectPlay How to install the Windows 10 old version component DirectPlay Dec 28, 2023 pm 03:43 PM

Many users always encounter some problems when playing some games on win10, such as screen freezes and blurred screens. At this time, we can solve the problem by turning on the directplay function, and the operation method of the function is also Very simple. How to install directplay, the old component of win10 1. Enter "Control Panel" in the search box and open it 2. Select large icons as the viewing method 3. Find "Programs and Features" 4. Click on the left to enable or turn off win functions 5. Select the old version here Just check the box

How to achieve point-to-point communication through PHP and P2P protocol How to achieve point-to-point communication through PHP and P2P protocol Jul 28, 2023 pm 10:13 PM

How to realize point-to-point communication through PHP and P2P protocol. With the development of the Internet, peer-to-peer (P2P) communication has gradually become an important communication method. Compared with the traditional client-server communication method, P2P communication has better stability and scalability. In this article, we will introduce how to use PHP with the P2P protocol to achieve peer-to-peer communication and provide corresponding code examples. First, we need to understand the basic principles of P2P communication. The P2P protocol allows multiple computers to directly

Analysis of communication between Vue and server: How to deal with network disconnection Analysis of communication between Vue and server: How to deal with network disconnection Aug 10, 2023 am 10:55 AM

Analysis of Vue and server-side communication: Strategies for dealing with network outages Introduction: In modern web development, Vue.js has become a widely used front-end framework. However, due to the instability of the network environment, handling disconnections is an important issue that we need to consider. This article will analyze how to handle network disconnection in Vue and give corresponding code examples. 1. Analysis of disconnection situations When the network conditions are good, Vue can communicate with the server through Ajax requests or WebSocket. but,

A brief history of broadband Internet technology A brief history of broadband Internet technology Apr 16, 2024 am 09:00 AM

In today's digital age, broadband has become a necessity for each of us and every family. Without it, we would be restless and restless. So, do you know the technical principles behind broadband? From the earliest 56k "cat" dial-up to the current Gigabit cities and Gigabit homes, what kind of changes has our broadband technology experienced? In today’s article, let’s take a closer look at the “Broadband Story”. Have you seen this interface between █xDSL and ISDN? I believe that many friends born in the 70s and 80s must have seen it and are very familiar with it. That's right, this was the interface for "dial-up" when we first came into contact with the Internet. That was more than 20 years ago, when Xiao Zaojun was still in college. In order to surf the Internet, I

How to open the settings of the old version of win10 components How to open the settings of the old version of win10 components Dec 22, 2023 am 08:45 AM

Win10 old version components need to be turned on by users themselves in the settings, because many components are usually closed by default. First we need to enter the settings. The operation is very simple. Just follow the steps below. Where are the win10 old version components? Open 1. Click Start, then click "Win System" 2. Click to enter the Control Panel 3. Then click the program below 4. Click "Enable or turn off Win functions" 5. Here you can choose what you want to open

The development history of wireless mice The development history of wireless mice Jun 12, 2024 pm 08:52 PM

Original title: "How does a wireless mouse become wireless?" 》Wireless mice have gradually become a standard feature of today’s office computers. From now on, we no longer have to drag long cords around. But, how does a wireless mouse work? Today we will learn about the development history of the No.1 wireless mouse. Did you know that the wireless mouse is now 40 years old? In 1984, Logitech developed the world's first wireless mouse, but this wireless mouse used infrared as a The signal carrier is said to look like the picture below, but later failed due to performance reasons. It was not until ten years later in 1994 that Logitech finally successfully developed a wireless mouse that works at 27MHz. This 27MHz frequency also became the wireless mouse for a long time.

Methods and techniques for implementing Socket communication in PHP Methods and techniques for implementing Socket communication in PHP Mar 07, 2024 pm 02:06 PM

PHP is a commonly used development language that can be used to develop various web applications. In addition to common HTTP requests and responses, PHP also supports network communication through Sockets to achieve more flexible and efficient data interaction. This article will introduce the methods and techniques of how to implement Socket communication in PHP, and attach specific code examples. What is Socket Communication Socket is a method of communication in a network that can transfer data between different computers. by S

See all articles