Home >Web Front-end >Vue.js >How to communicate between vue components? Method introduction

How to communicate between vue components? Method introduction

青灯夜游
青灯夜游forward
2020-10-26 17:54:452235browse

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 src="js/vue.js"></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>This is child component 1</h2>
        </template>
        
        <template id="child-component2">
            <h2>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>This is child component 1</h2>
        </template>
        
        <template id="child-component2">
            <h2>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>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:cnblogs.com. If there is any infringement, please contact admin@php.cn delete