search
HomeWeb Front-endVue.jsHow to communicate between vue components? Method introduction
How to communicate between vue components? Method introductionOct 26, 2020 pm 05:54 PM
vueComponent communication

How to communicate between vue components? Method introduction

Component communication

Although a child component can use this.$parent to access its parent component and any instance on its parent chain, Child components should avoid relying directly on the data of the parent component and try to explicitly use props to pass data.

In addition, it is a very bad practice to modify the state of the parent component in the child component, because:

  • This makes the parent component and the child component tightly coupled;

  • It is difficult to understand the status of the parent component only by looking at it. Because it may be modified by any subcomponent! Ideally, only the component itself can modify its state.

Each Vue instance is an event trigger:

  • $on() - listen for events.

  • $emit() - dispatches events up the scope chain. (Trigger event)

  • $dispatch() - Dispatch an event, which bubbles up along the parent chain.

  • $broadcast()——Broadcast the event and propagate the event downward to all descendants.

Monitoring and triggering

v-on listens for custom events:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <!--子组件模板-->
        <template id="child-template">
            <input v-model="msg" />
            <button v-on:click="notify">Dispatch Event</button>
        </template>
        <!--父组件模板-->
        <div id="events-example">
            <p>Messages: {{ messages | json }}</p>
            <child v-on:child-msg="handleIt"></child>
        </div>
    </body>
    <script src="js/vue.js"></script>
    <script>
//        注册子组件
//        将当前消息派发出去
        Vue.component(&#39;child&#39;, {
            template: &#39;#child-template&#39;,
            data: function (){
                return { msg: &#39;hello&#39; }
            },
            methods: {
                notify: function() {
                    if(this.msg.trim()){
                        this.$dispatch(&#39;child-msg&#39;,this.msg);
                        this.msg = &#39;&#39;;
                    }
                }
            }
        })
//        初始化父组件
//        在收到消息时将事件推入一个数组中
        var parent = new Vue({
            el: &#39;#events-example&#39;,
            data: {
                messages: []
            },
            methods:{
                &#39;handleIt&#39;: function(){
                    alert("a");
                }
            }
        })
    </script>
</html>

How to communicate between vue components? Method introduction

The parent component can directly use v-on where the child component is used to listen to the events triggered by the child component:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <div id="counter-event-example">
          <p>{{ total }}</p>
          <button-counter v-on:increment="incrementTotal"></button-counter>
          <button-counter v-on:increment="incrementTotal"></button-counter>
        </div>
    </body>
    <script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
    <script type="text/javascript">
        Vue.component(&#39;button-counter&#39;, {
          template: &#39;<button v-on:click="increment">{{ counter }}</button>&#39;,
          data: function () {
            return {
              counter: 0
            }
          },
          methods: {
            increment: function () {
              this.counter += 1
              this.$emit(&#39;increment&#39;)
            }
          },
        })
        new Vue({
          el: &#39;#counter-event-example&#39;,
          data: {
            total: 0
          },
          methods: {
            incrementTotal: function () {
              this.total += 1
            }
          }
        })
    </script>
</html>

How to communicate between vue components? Method introduction

Listen to a native element on the root element of a component event. You can use .native to modify v-on. For example:

<my-component v-on:click.native="doTheThing"></my-component>

Dispatch event - $dispatch()

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <div id="app">
            <p>Messages: {{ messages | json }}</p>
            <child-component></child-component>
        </div>
        <template id="child-component">
            <input v-model="msg" />
            <button v-on:click="notify">Dispatch Event</button>
        </template>

    <script ></script>
    <script>
        // 注册子组件
        Vue.component(&#39;child-component&#39;, {
            template: &#39;#child-component&#39;,
            data: function() {
                return {
                    msg: &#39;&#39;
                }
            },
            methods: {
                notify: function() {
                    if (this.msg.trim()) {
                        this.$dispatch(&#39;child-msg&#39;, this.msg)
                        this.msg = &#39;&#39;
                    }
                }
            }
        })
    
        // 初始化父组件
        new Vue({
            el: &#39;#app&#39;,
            data: {
                messages: []
            },
            events: {
                &#39;child-msg&#39;: function(msg) {
                    this.messages.push(msg)
                }
            }
        })
    </script>
    </body>
</html>

How to communicate between vue components? Method introduction

  1. The button element of the sub-component is bound to the click event. This event points to the notify method

  2. When the notify method of the child component is processed, $dispatch is called, the event is dispatched to the child-msg event of the parent component, and the event is provided with A msg parameter

  3. The child-msg event is defined in the events option of the parent component. After the parent component receives the dispatch of the child component, it calls the child-msg event.

Broadcast event - $broadcast()

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <div id="app">
            <input v-model="msg" />
            <button v-on:click="notify">Broadcast Event</button>
            <child-component></child-component>
        </div>
        
        <template id="child-component">
            <ul>
                <li v-for="item in messages">
                    父组件录入了信息:{{ item }}
                </li>
            </ul>
        </template>

    <script src="js/vue.js"></script>
    <script>
        // 注册子组件
        Vue.component(&#39;child-component&#39;, {
            template: &#39;#child-component&#39;,
            data: function() {
                return {
                    messages: []
                }
            },
            events: {
                &#39;parent-msg&#39;: function(msg) {
                    this.messages.push(msg)
                }
            }
        })
        // 初始化父组件
        new Vue({
            el: &#39;#app&#39;,
            data: {
                msg: &#39;&#39;
            },
            methods: {
                notify: function() {
                    if (this.msg.trim()) {
                        this.$broadcast(&#39;parent-msg&#39;, this.msg)
                    }
                }
            }
        })
    </script>
    </body>
</html>

The opposite of dispatching events. The former is bound in the child component and calls $dispatch to dispatch to the parent component; the latter is bound in the parent component and calls $broadcast to broadcast to the child component.

Access between parent and child components

  • Parent component accesses child components: use $children or $refs

  • Child components access parent components: use $parent

  • Child components access root components: use $root

$children:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <div id="app">
            <parent-component></parent-component>
        </div>
        
        <template id="parent-component">
            <child-component1></child-component1>
            <child-component2></child-component2>
            <button v-on:click="showChildComponentData">显示子组件的数据</button>
        </template>
        
        <template id="child-component1">
            <h2 id="This-nbsp-is-nbsp-child-nbsp-component-nbsp">This is child component 1</h2>
        </template>
        
        <template id="child-component2">
            <h2 id="This-nbsp-is-nbsp-child-nbsp-component-nbsp">This is child component 2</h2>
        </template>
        <script src="js/vue.js"></script>
        <script>
            Vue.component(&#39;parent-component&#39;, {
                template: &#39;#parent-component&#39;,
                components: {
                    &#39;child-component1&#39;: {
                        template: &#39;#child-component1&#39;,
                        data: function() {
                            return {
                                msg: &#39;child component 111111&#39;
                            }
                        }
                    },
                    &#39;child-component2&#39;: {
                        template: &#39;#child-component2&#39;,
                        data: function() {
                            return {
                                msg: &#39;child component 222222&#39;
                            }
                        }
                    }
                },
                methods: {
                    showChildComponentData: function() {
                        for (var i = 0; i < this.$children.length; i++) {
                            alert(this.$children[i].msg)
                        }
                    }
                }
            })
        
            new Vue({
                el: &#39;#app&#39;
            })
        </script>
    </body>
</html>

How to communicate between vue components? Method introduction

$ref can specify the index ID for child components:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <div id="app">
            <parent-component></parent-component>
        </div>
        
        <template id="parent-component">
            <!--<child-component1></child-component1>
            <child-component2></child-component2>-->
            <child-component1 v-ref:cc1></child-component1>
            <child-component2 v-ref:cc2></child-component2>
            <button v-on:click="showChildComponentData">显示子组件的数据</button>
        </template>
        
        <template id="child-component1">
            <h2 id="This-nbsp-is-nbsp-child-nbsp-component-nbsp">This is child component 1</h2>
        </template>
        
        <template id="child-component2">
            <h2 id="This-nbsp-is-nbsp-child-nbsp-component-nbsp">This is child component 2</h2>
        </template>
        <script src="js/vue.js"></script>
        <script>
            Vue.component(&#39;parent-component&#39;, {
                template: &#39;#parent-component&#39;,
                components: {
                    &#39;child-component1&#39;: {
                        template: &#39;#child-component1&#39;,
                        data: function() {
                            return {
                                msg: &#39;child component 111111&#39;
                            }
                        }
                    },
                    &#39;child-component2&#39;: {
                        template: &#39;#child-component2&#39;,
                        data: function() {
                            return {
                                msg: &#39;child component 222222&#39;
                            }
                        }
                    }
                },
                methods: {
                    showChildComponentData: function() {
//                        for (var i = 0; i < this.$children.length; i++) {
//                            alert(this.$children[i].msg)
//                        }
                        alert(this.$refs.cc1.msg);
                        alert(this.$refs.cc2.msg);
                    }
                }
            })
            new Vue({
                el: &#39;#app&#39;
            })
        </script>
    </body>
</html>

The effect is the same as $children.

$parent:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <div id="app">
            <parent-component></parent-component>
        </div>
        
        <template id="parent-component">
            <child-component></child-component>
        </template>
        
        <template id="child-component">
            <h2 id="This-nbsp-is-nbsp-a-nbsp-child-nbsp-component">This is a child component</h2>
            <button v-on:click="showParentComponentData">显示父组件的数据</button>
        </template>
        
        <script src="js/vue.js"></script>
        <script>
            Vue.component(&#39;parent-component&#39;, {
                template: &#39;#parent-component&#39;,
                components: {
                    &#39;child-component&#39;: {
                        template: &#39;#child-component&#39;,
                        methods: {
                            showParentComponentData: function() {
                                alert(this.$parent.msg)
                            }
                        }
                    }
                },
                data: function() {
                    return {
                        msg: &#39;parent component message&#39;
                    }
                }
            })
            new Vue({
                el: &#39;#app&#39;
            })
        </script>
    </body>
</html>

How to communicate between vue components? Method introduction

As mentioned at the beginning, it is not recommended to modify the state of the parent component in the child component.

Non-parent-child component communication

Sometimes components with non-parent-child relationships also need to communicate. In a simple scenario, use an empty Vue instance as the central event bus:

var bus = new Vue()
// 触发组件 A 中的事件
bus.$emit(&#39;id-selected&#39;, 1)
// 在组件 B 创建的钩子中监听事件
bus.$on(&#39;id-selected&#39;, function (id) {
    // ...
})

Related recommendations:

2020 Summary of front-end vue interview questions (With answers)

vue tutorial recommendation: The latest 5 vue.js video tutorial selections in 2020

More programming-related knowledge, Please visit: Introduction to Programming! !

The above is the detailed content of How to communicate between vue components? Method introduction. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
5 款适合国内使用的 Vue 移动端 UI 组件库5 款适合国内使用的 Vue 移动端 UI 组件库May 05, 2022 pm 09:11 PM

本篇文章给大家分享5 款适合国内使用的 Vue 移动端 UI 组件库,希望对大家有所帮助!

聊聊vue指令中的修饰符,常用事件修饰符总结聊聊vue指令中的修饰符,常用事件修饰符总结May 09, 2022 am 11:07 AM

本篇文章带大家聊聊vue指令中的修饰符,对比一下vue中的指令修饰符和dom事件中的event对象,介绍一下常用的事件修饰符,希望对大家有所帮助!

通过9个Vue3 组件库,看看聊前端的流行趋势!通过9个Vue3 组件库,看看聊前端的流行趋势!May 07, 2022 am 11:31 AM

本篇文章给大家分享9个开源的 Vue3 组件库,通过它们聊聊发现的前端的流行趋势,希望对大家有所帮助!

react与vue的虚拟dom有什么区别react与vue的虚拟dom有什么区别Apr 22, 2022 am 11:11 AM

react与vue的虚拟dom没有区别;react和vue的虚拟dom都是用js对象来模拟真实DOM,用虚拟DOM的diff来最小化更新真实DOM,可以减小不必要的性能损耗,按颗粒度分为不同的类型比较同层级dom节点,进行增、删、移的操作。

VSCode插件分享:一个实时预览Vue/React组件的插件VSCode插件分享:一个实时预览Vue/React组件的插件Mar 17, 2022 pm 08:07 PM

在VSCode中开发Vue/React组件时,怎么实时预览组件?本篇文章就给大家分享一个VSCode 中实时预览Vue/React组件的插件,希望对大家有所帮助!

Vue组件通信:使用回调函数进行组件通信Vue组件通信:使用回调函数进行组件通信Jul 09, 2023 pm 07:42 PM

Vue组件通信:使用回调函数进行组件通信在Vue应用程序中,有时候我们需要让不同的组件之间进行通信,以便它们可以共享信息和相互协作。Vue提供了多种方式来实现组件之间的通信,其中一种常用的方式是使用回调函数。回调函数是一种将一个函数作为参数传递给另一个函数并在特定事件发生时被调用的机制。在Vue中,我们可以利用回调函数来实现组件之间的通信,使得一个组件可以在

手把手带你使用Vue + Laravel开发一个简单的 CRUD 应用手把手带你使用Vue + Laravel开发一个简单的 CRUD 应用Apr 15, 2022 pm 08:55 PM

本篇文章给大家分享一个Vue+Laravel开发教程,介绍一下怎么使用 Vue.js 和 Laravel 共建一个简单的 CRUD 应用,希望对大家有所帮助!

深入浅析vue3+vite中怎么使用svg图标深入浅析vue3+vite中怎么使用svg图标Apr 28, 2022 am 10:48 AM

svg图片在项目中使用的非常广泛,下面本篇文章带大家介绍一下如何在vue3 + vite 中使用svg图标,希望对大家有所帮助!

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.