Table of Contents
Written in front
What are Vue components?
Communication between Vue components
Communication between parent component and child component
Method 1: props
Method 2 uses $children
The child component communicates with the parent component
Method 1: Using vue events
Method 2: Modify the parent component data by modifying the props passed by the parent component
Method 3: Use $parent
Data transfer between non-parent-child components and sibling components
Multi-level parent-child component communication:
Complex single-page application data management
Home Web Front-end JS Tutorial About communication issues in Vue.js components

About communication issues in Vue.js components

Oct 24, 2017 am 09:29 AM
javascript vue.js question

Written in front

Because I am very interested in Vue.js, and the technology stack I usually work on is also Vue.js, I have spent some time studying the Vue.js source code in the past few months, and Summary and output were made.

What are Vue components?

Component is one of the most powerful features of Vue.js. Components can extend HTML elements, encapsulating reusable code. At a high level, a component is a custom element to which Vue.js's compiler adds special functionality. In some cases, components can also take the form of native HTML elements, extended with the is attribute.

Communication between Vue components

Communication between parent component and child component

Method 1: props

Using props, the parent component can Use props to pass data to child components.

Parent component vue template father.vue

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

<template>

    <child :msg="message"></child>

</template>

 

<script>

 

import child from &#39;./child.vue&#39;;

 

export default {

    components: {

        child

    },

    data () {

        return {

            message: &#39;father message&#39;;

        }

    }

}

</script>

Copy after login

Child component vue template child.vue

1

2

3

4

5

6

7

8

9

10

11

12

13

14

<template>

    <p>{{msg}}</p>

</template>

 

<script>

export default {

    props: {

        msg: {

            type: String,

            required: true

        }

    }

}

</script>

Copy after login

Method 2 uses $children

Using $children can be used Access child components from parent components.

The child component communicates with the parent component

Method 1: Using vue events

The parent component passes the event method to the child component, and the child component triggers the event through $emit. Callback to parent component.

Parent component vue template father.vue

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

<template>

    <child @msgFunc="func"></child>

</template>

 

<script>

 

import child from &#39;./child.vue&#39;;

 

export default {

    components: {

        child

    },

    methods: {

        func (msg) {

            console.log(msg);

        }

    }

}

</script>

Copy after login

Child component vue template child.vue

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

<template>

    <button @click="handleClick">点我</button>

</template>

 

<script>

export default {

    props: {

        msg: {

            type: String,

            required: true

        }

    },

    methods () {

        handleClick () {

            //........

            this.$emit(&#39;msgFunc&#39;);

        }

    }

}

</script>

Copy after login

Method 2: Modify the parent component data by modifying the props passed by the parent component

This method can only be used when the parent component passes a reference variable. Literal variables cannot achieve the corresponding effect. Because the drinking variable ultimately points to the same memory address, whether it is the data in the parent component or the data in the props obtained by the child component, so modifying the data in the props in the child component modifies the data in the parent component.

But this is not recommended. It is not recommended to directly modify the value of props. If the data is used to display modifications, in actual development I often put it into data and pass it back when needed. The parent component then uses events to return data. This keeps the components independent and decoupled, and does not cause abnormal data flow confusion due to the use of the same data. Data is only transmitted through specific interfaces to modify the data, and the internal data status is managed by specialized data.

Method 3: Use $parent

Use $parent to access the data of the parent component.

Data transfer between non-parent-child components and sibling components

For non-parent-child component communication, Vue officially recommends using a Vue instance as the central event bus.

Vue has an internal event mechanism, you can refer to the source code.

$on method is used to listen to an event.

$emit is used to trigger an event.

1

2

3

4

5

6

7

8

9

10

/*新建一个Vue实例作为中央事件总嫌*/

let event = new Vue();

 

/*监听事件*/

event.$on(&#39;eventName&#39;, (val) => {

    //......do something

});

 

/*触发事件*/

event.$emit(&#39;eventName&#39;, &#39;this is a message.&#39;);

Copy after login

Multi-level parent-child component communication:

In Vue1.0, two methods, $broadcast and $dispatch, are implemented to broadcast (or dispatch) to child components (or parent components). When the child component (or parent component) listens to the event and returns true, the event will continue to be broadcast (or dispatched) to the grandchild-level component. But this method has been removed in Vue2.0.

When I was studying the open source component library element of Ele.me, I found that they re-implemented the broadcast and dispatch methods and introduced them in the form of mixin. For details, please refer to "Talk about element component library broadcast and dispatch". But it is slightly different from the two method implementations of Vue1.0. These two methods implement the functions of event broadcasting to descendant components and event dispatching to multi-level parent components. But it is not event broadcasting in a broad sense. It requires specifying a commentName to broadcast (dispatch) events to the component with the specified component name.

In fact, the internal implementation of these two methods still uses $parent and $children, which are used to traverse child nodes or query parent nodes step by step. When the specified component name is accessed, $emit is called to trigger Specify event.

Complex single-page application data management

When the application is complex enough, please use vuex for data management.

The above is the detailed content of About communication issues in Vue.js 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
1653
14
PHP Tutorial
1251
29
C# Tutorial
1224
24
Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to solve the problem that jQuery cannot obtain the form element value How to solve the problem that jQuery cannot obtain the form element value Feb 19, 2024 pm 02:01 PM

To solve the problem that jQuery.val() cannot be used, specific code examples are required. For front-end developers, using jQuery is one of the common operations. Among them, using the .val() method to get or set the value of a form element is a very common operation. However, in some specific cases, the problem of not being able to use the .val() method may arise. This article will introduce some common situations and solutions, and provide specific code examples. Problem Description When using jQuery to develop front-end pages, sometimes you will encounter

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

What are the questions in the Rulong 8 Wine Master exam? What are the questions in the Rulong 8 Wine Master exam? Feb 02, 2024 am 10:18 AM

What are the questions involved in the Yulong 8 Wine Master exam? What is the corresponding answer? How to pass the exam quickly? There are many questions that need to be answered in the Master of Wine Examination activities, and we can refer to the answers to solve them. These questions all involve knowledge of wine. If you need a reference, let’s take a look at the detailed analysis of the answers to the Yakuza 8 Wine Master exam questions! Detailed explanation of answers to questions in the Rulong 8 Wine Master exam 1. Questions about "wine". This is a distilled liquor produced by a distillery established by the royal family. It is brewed from the sugar of sugarcane grown in large quantities in Hawaii. What is the name of this wine? Answer: Rum 2. Question about "wine". The picture shows a drink made from dry ginseng and dry vermouth. It is characterized by the addition of olives and is known as "cockney"

How to solve the problem of the start menu that cannot be used after win11 installation How to solve the problem of the start menu that cannot be used after win11 installation Jan 06, 2024 pm 05:14 PM

Many users have tried to update the win11 system, but found that the start menu cannot be used after the update. This may be because there is a problem with the latest update. We can wait for Microsoft to fix or uninstall these updates to solve the problem. Let's take a look at it together. Solution. What to do if the start menu cannot be used after win11 is installed. Method 1: 1. First open the control panel in win11. 2. Then click the "Uninstall a program" button below the program. 3. Enter the uninstall interface and find "View installed updates" in the upper left corner. 4. After entering, you can view the update time in the update information and uninstall all recent updates. Method 2: 1. In addition, we can also directly download the win11 system without updates. 2. This is a product without the most

Vue.js vs. React: Project-Specific Considerations Vue.js vs. React: Project-Specific Considerations Apr 09, 2025 am 12:01 AM

Vue.js is suitable for small and medium-sized projects and fast iterations, while React is suitable for large and complex applications. 1) Vue.js is easy to use and is suitable for situations where the team is insufficient or the project scale is small. 2) React has a richer ecosystem and is suitable for projects with high performance and complex functional needs.

Frequently Asked Questions about Wuhuami's new breakthrough test: February 28, we look forward to your arrival! Frequently Asked Questions about Wuhuami's new breakthrough test: February 28, we look forward to your arrival! Feb 26, 2024 pm 05:22 PM

Wuhua Mixin has confirmed that it will conduct a breaking test on February 28. This time we will mainly solve the common problems of the breaking test, including whether you have participated in previous tests, are you eligible this time, the start and end of the test, and the pre-download time? Let’s take a look at what device platforms are supported and other content. Frequently Asked Questions about Wuhuami’s new breakthrough test: February 28, we look forward to your arrival! 1. What is the nature of the "breaking test"? This test is a limited billing and file deletion test for Android. After the test, the game data of this test will be deleted. 2. Have you ever participated in the "Opening Test" or "Entry Test"? Do you have the qualifications to participate in the "Breaking Test" this time? If you have participated in the "Opening Test" or "Entry Test", please scan the QR code below to go to " To players who have participated in the closed beta

Is vue.js hard to learn? Is vue.js hard to learn? Apr 04, 2025 am 12:02 AM

Vue.js is not difficult to learn, especially for developers with a JavaScript foundation. 1) Its progressive design and responsive system simplify the development process. 2) Component-based development makes code management more efficient. 3) The usage examples show basic and advanced usage. 4) Common errors can be debugged through VueDevtools. 5) Performance optimization and best practices, such as using v-if/v-show and key attributes, can improve application efficiency.

See all articles