Three Ways of Communication between Vue Components

Keywords: Javascript Vue Attribute

Recent reading Liang Dian's book Vue.js Actual Warfare, I feel quite fruitful, so I hereby record some practical skills of price comparison.

Component is the core design idea of MVVM framework. Componentization of each function point is more conducive to reuse in the project. It is similar to the encapsulation of one of the three major features of object-oriented on our server side. It encapsulates complex code that will be called many times into components and registers it where it needs to be called. The front-end code designed in this way is easy to transplant and reuse across projects.

The relationship between components can be divided into parent-child component brothers component and cross-level component, etc. Data is exchanged between components and communication is mainly carried out in three ways:

  1. Central Event Bus (Non-parent-child Component Communication)
  2. Parent chain
  3. Subcomponent Index

Let's talk about these three ways of communication.

I. Central Event Bus

The name of this thing is frightening, but in fact it is a well-understood way of communication, let's code it.

  

<body>
    <div id="app">
        {{message}}
        <tempcomponent-a></tempcomponent-a>
    </div>
    <script>
        var middleware = new Vue();

        Vue.component('tempcomponent-a', {
            template: '<button @click="handleEvent">Transfer events</button>',
            methods: {
                handleEvent: function () {
                    middleware.$emit('on-message', 'From components tempcomponent-a Content');
                }
            }
        });
        var app = new Vue({
            el: '#app',
            data: {
                message: ''
            },
            mounted: function () {
                var _this = this;
                middleware.$on('on-message', function (msg) {
                    _this.message = msg;
                })
            },
        });
    </script>
</body>

In the above code, the empty Vue instance "middleware" is our so-called central event bus. We can see that it is responsible for sending events in the self-component "tempcomponent-a". In our main Vue instance app, we can get the content sent by the sub-component by listening for "middleware". My understanding is that the central event bus is like a temporary variable when we exchange data. It handles the results in the middle and then returns the message to the requester. Its responsibility is to mediate. This empty Vue instance can also add data, methods and other options, which can be used as public.

2. Parent chain $parent

The word parent chain is easy to understand. As the name implies, it is the parent object of a component, which can be manipulated directly by $parent inside the component.

<body>
    <div id="app">
        {{message}}
        <tempcomponent-a></tempcomponent-a>
    </div>
    <script>
        Vue.component('tempcomponent-a', {
            template: '<button @click="handleEvent">Modify data directly through parent chains</button>',
            methods: {
                handleEvent: function () {
                    this.$parent.message = 'From components tempcomponent-a News';
                }
            }
        });
        var app = new Vue({
            el: '#app',
            data: {
                message: ''
            }
        })
    </script>
</body>

From the above code, we can see that it is very simple to use parent chain $parent directly to manipulate the attributes of the parent object within the self-component.

Subcomponent index ref &$refs

The sub-component is also well understood. It operates on the parent object. Generally speaking, there are many sub-components in the parent container, so each component needs to set a special property ref to specify a unique name for itself.

<body>
    <div id="app">
        <button @click="handleRef">adopt ref Get subcomponent instances</button>
        <tempcomponent-a ref="comA"></tempcomponent-a>
    </div>
    <script>
        Vue.component('tempcomponent-a', {
            template: '<div>Sub components</div>',
            data: function () {
                return {
                    message: 'Subcomponent content'
                }
            }
        });
        var app = new Vue({
            el: '#app',
            methods: {
                handleRef: function () {
                    var msg = this.$refs.comA.message;
                    console.log(msg);
                }
            }
        })
    </script>
</body>

As can be seen from the code, when we create ref attribute directly on the component and want to operate on the sub-component in the parent object, we can access the ref attribute directly through $refs. plus the component's unique access to the ref attribute. Note that $refs is filled in after the subcomponent rendering is complete, and is not responsive. Avoid using $refs in computational attributes and templates

Posted by darktimesrpg on Wed, 08 May 2019 06:21:40 -0700