Talk about several postures of communication between Vue.js components

write in front

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

The original address of the article: https://github.com/answershuto/learnVue .

In the process of learning, I added Chinese comments to Vue https://github.com/answershuto/learnVue/tree/master/vue-src , I hope it can be helpful to other friends who want to learn Vue source code.

There may be some deviations in understanding. You are welcome to raise issues and point out, learn together and make progress together.

What is a Vue component?

Components are 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 the Vue.js compiler adds special functionality. In some cases, components can also be in the form of native HTML elements, extended with the is attribute.

<br /> <br />

Communication between Vue components

Parent component communicates to child component

Method 1: props

Using props , parent components can use props to pass data to child components.

Parent component vue template father.vue

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

<script>

import child from './child.vue';

export default {
    components: {
        child
    },
    data () {
        return {
            message: 'father message';
        }
    }
}
</script>

Child component vue template child.vue

<template>
    <div>{{msg}}</div>
</template>

<script>
export default {
    props: {
        msg: {
            type: String,
            required: true
        }
    }
}
</script>

<br />

Method 2 uses $children

Use $children to access child components in parent components.

<br /> <br />

Child component communicates with parent component

<br />

Method 1: Use vue events

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

Parent component vue template father.vue

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

<script>

import child from './child.vue';

export default {
    components: {
        child
    },
    methods: {
        func (msg) {
            console.log(msg);
        }
    }
}
</script>

Child component vue template child.vue

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

<script>
export default {
    props: {
        msg: {
            type: String,
            required: true
        }
    },
    methods () {
        handleClick () {
            //........
            this.$emit('msgFunc');
        }
    }
}
</script>

<br />

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, and 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, modifying the data of the props in the child component modifies the data of the parent component.

But it is not recommended to do this, and it is not recommended to directly modify the value of props. If the data is used for display modification, I often put it in the data in actual development, and use it when it needs to be passed back to the parent component. The event returns data. In this way, the components are kept independent and decoupled, and the data flow will not be abnormally chaotic due to the use of the same data. The purpose of modifying the data is only achieved by passing the data through a specific interface, and the internal data state is managed by the special data.

<br />

Method 3: Use $parent

Use $parent to access parent component data.

<br /> <br />

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 .

There is an event mechanism inside Vue, you can refer to the source code .

The $on method is used to listen for an event.

$emit is used to trigger an event.

/*新建一个Vue实例作为中央事件总嫌*/
let event = new Vue();

/*监听事件*/
event.$on('eventName', (val) => {
    //......do something
});

/*触发事件*/
event.$emit('eventName', 'this is a message.');

<br /> <br />

Multi-level parent-child component communication:

In Vue1.0, the $broadcast and $dispatch methods are implemented to broadcast (or dispatch) to the child component (or parent component), and when the child component (or parent component) listens for an event and returns true, it will be sent to the child component (or parent component). Grandpa-level components continue to broadcast (or dispatch) events. But this method has been removed in Vue2.0.

When I was learning Ele.me's open source component library element , I found that they reimplemented the methods of broadcast and dispatch, and introduced them in the form of mixins. For details, please refer to "Telling About Broadcast and Dispatch of the Element Component Library" . But it is slightly different from the two methods of Vue1.0. These two methods implement the function of broadcasting events to descendant components and dispatching events to multi-level parent components. But it is not an event broadcast in a broad sense, it needs to specify a commentName to broadcast (dispatch) events to the specified component name component.

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

<br /> <br />

Complex Single Page Application Data Management

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

about

Author: Ran Mo

Email:[email protected] or [email protected]

Github: https://github.com/answershuto

Blog:http://answershuto.github.io/

Zhihu homepage: https://www.zhihu.com/people/cao-yang-49/activities

Know the column: https://zhuanlan.zhihu.com/ranmo

Nuggets: https://juejin.im/user/58f87ae844d9040069ca7507

osChina:https://my.oschina.net/u/3161824/blog

Please indicate the source when reprinting, thank you.

Welcome to pay attention to my public number

{{o.name}}
{{m.name}}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324075696&siteId=291194637