Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities


preface

Components are one of the most powerful features of vue.js, and component instances are scoped independently of each other, which means that data from different components cannot be referenced to each other. In general, components can have the following relationships:

What is the Vue component?

Components are one of the most powerful features of vue.js, and component instances are scoped independently of each other, which means that data from different components cannot be referenced to each other. This article mainly introduces six modes of communication between VUE components, three of which are introduced in this article

Second, specific introduction

How to choose an effective communication mode for different usage scenarios? This is the subject of our discussion. This article summarizes several ways to communicate between VUE components, Examples are props, emit/emit /emit /on, vuex, parent/parent /parent /children, attrs/attrs /attrs /listeners/provide/inject, To explain the differences and use scenarios in easy to understand examples, I hope to have some help for small partners

Method 1: props / $emit

Parent component A passes props to child component B, and B to A is realized by $emit in component B and V-on in component A.

2.2.1 Parent Components transmit values to child components

Vue gets data Users from app. vue: [“Henry”,”Bucky”,”Emily”]

The code is as follows (example) :

/ / App. Vue parent component
<template>
<div id="app">
<users v-bind:users="users"></users>// The former defines a custom name for child component invocation, while the latter passes a data name
</div>
</template>
<script>
import Users from "./components/Users"
export default {
name: 'App',
data(){
return{
users:["Henry"."Bucky"."Emily"]
}
},
components:{
"users":Users
}
}
/ / users subcomponents
<template>
<div class="hello">
<ul>
<li v-for="user in users">{{user}}</li>// Iterate over the passed value and render to the page
</ul>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
props:{
users:{ // This is the parent component neutron tag custom name
type:Array,
required:true
}
}
}
</script>
Copy the code

Summary: The parent component passes data down to the child component via props. Note: There are three forms of data in the component: Data, props, and computed

2.2.2 Child component passing Value to Parent (in the form of an event) Let’s use an example to illustrate how a child component passes value to its parent: When we click “vue.js Demo”, the child component passes the value to the parent component, the text changes from the original “pass is a value” to “the child to the parent component value”, to achieve the child component to the parent component value transfer.

The code is as follows (example) :

/ / child component
<template>
<header>
<h1 @click="changeTitle">{{title}}</h1>// Bind a click event
</header>
</template>
<script>
export default {
name: 'app-header',
data() {
return {
title:"Vue.js Demo"
}
},
methods:{
changeTitle() {
this.$emit("titleChanged"."Child passes value to parent");// Custom event pass value "child to parent"
}
}
}
</script>
/ / the parent component
<template>
<div id="app">
<app-header v-on:titleChanged="updateTitle" ></app-header>// Be consistent with the child component titleChanged custom event
// updateTitle($event) accepts the text passed in
<h2>{{title}}</h2>
</div>
</template>
<script>
import Header from "./components/Header"
export default {
name: 'App',
data(){
return{
title:"I'm passing a value."
}
},
methods:{
updateTitle(e){ // Declare this function
this.title = e;
}
},
components:{
"app-header":Header,
}
}
</script>
Copy the code

Summary: The child sends a message to the parent via Events. In fact, the child sends its data to the parent.

2.2 Method 2
e m i t / emit /
on

This approach uses an empty Vue instance as the central event bus (event hub) to trigger and listen for events, subtly and lightly enabling communication between any component, including parent, sibling, and cross-level. When our project was larger, we could have chosen a better state management solution, VUEX. 2.2.1. Specific implementation: The code is as follows (example) :

var Event=newVue(); $emit(Event name, data); $on(data => {});Copy the code

2.2.2. For example, there are three sibling components, namely A, B and C. How does C obtain the data of A or B

<div id="itany">
<my-a></my-a>
<my-b></my-b>
<my-c></my-c>
</div>
<template id="a"> <div> <h3>A component: {{name}}</h3> < button@click ="send"> sends data to the C component </button> </div> </template>
<template id="b"> <div> <h3>B component: {{age}}</h3> < button@click ="send"> sends the array to the C component </button> </div> </template>
<template id="c"> <div> <h3>C components: {{name}}, {{age}}</h3> </div> </template>
<script>
var Event = new Vue();// Define an empty Vue instance
var A = {
template: '#a',
data() {
return {
name: 'tom'
}
},
methods: {
send() {
Event.$emit('data-a'.this.name);
}
}
}
var B = {
template: '#b',
data() {
return {
age: 20
}
},
methods: {
send() {
Event.$emit('data-b'.this.age);
}
}
}
var C = {
template: '#c',
data() {
return {
name: ", the age: ""}}, mounted () {/ / in the template compilation performed after the completion of the Event. $on ('data-a',name => {
this.name = name;// The arrow function does not generate a new this
})
Event.$on('data-b',age => {
this.age = age;
})
}
}
var vm = new Vue({
el: '#itany',
components: {
'my-a': A,
'my-b': B,
'my-c': C
}
}) ;
</script>
Copy the code

2.3 VuEX

Vuex implements a one-way data flow and stores data globally in a State. When a component wants to change the data in the State, it must advance the data through Mutation, which also provides a subscriber mode for external plug-in to call to obtain the update of State data. However, when all asynchronous operations (common in calling back-end interfaces to get updated data asynchronously) or batch synchronous operations need Action, but the Action cannot directly modify the State, and the State data still needs to be modified by Mutation. Finally, render to the view as the State changes.

2. Briefly introduce the functions of each module in the process:

Vue Components: Vue Components. On the HTML page, responsible for receiving user operations and other interactive behaviors, execute the Dispatch method to trigger corresponding actions to respond. Dispatch: Action action trigger method, the only method that can execute an action.

Actions: Action action processing module, triggered by $store.dispatch(‘ Action name ‘, data1) in the component. The mutation call is then triggered by commit(), indirectly updating the state. Responsible for handling all interactions received by Vue Components. Contains synchronous/asynchronous operations and supports multiple methods of the same name that are triggered in the order of registration. Requests to the background API are made in this module, including triggering other actions and submitting mutations. This module provides the encapsulation of promises to support the chain firing of actions.

Commit: State changes commit operation method. Committing for mutation is the only way to perform mutation. Mutations: A state change operation, triggered by the COMMIT (‘mutation name ‘) in actions. Is the only recommended method for Vuex to modify state. This method can only perform synchronous operations, and the method name must be globally unique. Some hooks will be exposed during the operation for state monitoring and so on.

State: page state management container object. Centralized storage of scattered data objects in Vue Components, globally unique, for unified state management. The data required for page display is read from this object, leveraging Vue’s fine-grained data response mechanism for efficient status updates. Getters: State Object reading method. This module is not listed separately and should be included in Render, where Vue Components read the global state object.

3.Vuex and localStorage Vuex is the state manager of VUE and stores responsive data. When the vuEX data is changed, copy the data and save it to localStorage. After refreshing, if there is saved data in localStorage, Take it out and replace the state in store.

let defaultCity = "Shanghai"                                                                                                                                                                                                        try { // Add a try... catch if (! defaultCity){ defaultCity = JSON.parse(window.localStorage.getItem('defaultCity')) } }catch(e){} export default new Vuex.Store({
state: {
city: defaultCity
},
mutations: {
changeCity(state, city) {
state.city = city
try {
window.localStorage.setItem('defaultCity', JSON.stringify(state.city));
// Make a copy of the data to localStorage when it changes
} catch (e) {}
}
}
})
Copy the code

Note that: In VUEX, all the states we save are arrays, while localStorage only supports strings, so we need to use JSON conversion:


JSON.stringify(state.subscribeList); 
// array -> string JSON.parse(window.localStorage.getItem("subscribeList")); // string -> array
Copy the code

conclusion

The common use scenarios can be divided into three categories:

Parent-child communication: the parent passes data to the child through props and the child passes data to the parent through events (emit). Can also communicate via parent/child chain (EMIT); Can also communicate via parent/child chain (EMIT); Parent / $children can also communicate (parent / $children); Ref can also access component instances; Provide/Inject API.

Brother communication: Vuex;

In the next article, we’ll look at three other ways to communicate between VUE components

The above is six ways of communication between VUE components (summary), the original is not easy, looking forward to your likes attention and forwarding comments 😜😜😜Copy the code