preface
In vue component development (1), the communication between parent and child components is introduced. In addition to the communication between parent and child components, there is also the communication between brother components. The so-called brother component refers to the use of two brother components a and B in the same component at the same time. Clicking on sub component a requires the response of another sub component B, then component A and component B are brother components. The communication between sibling components is also one of the common communication methods in vue component development. In order to solve the coupling between sibling components, the common coupling mode is generally adopted, that is, indirect coupling through a third party, as shown in the figure below
This communication mode is similar to the mediator mode in the design pattern. eventBus and vuex are similar to intermediaries. The components are not directly coupled with each other to ensure the independence and reusability of each component. VUE develops the communication between brother components. Small projects generally use eventBus, and large projects mostly use vuex.
eventBus
EventBus is also called event bus. The concept of using EventBus as a communication bridge is that all components share the same event center, and each component can register with the center to send and receive events. In vue, the existence form of EventBus is an independent js file.
[example] component A and component B communicate through eventbus. When clicking the button on the component, the msg value of component B will be sent to component A for display
- Create a bus JS file, which acts as the eventbus container. The code is as follows:
import Vue from 'vue'; export default new Vue
- Define the component ChildA, which is used to receive the data component and listen to the "clickBtn" event in ChildB through eventbus. Its code is as follows
<template> <div> <span>{{msg}}</span> </br> <span>B The message sent by the component is:{{recMsg}}</span> </div> </template>
<script> import eventBus from '../utils/Bus.js' //Introduce bus js export default { name: 'v-childA', data() { return { msg: 'This is A Component message', recMsg: 'www' } }, mounted: function() { var that = this; //Note: clickBtn is the name of the event to be sent and listened to, and target is the data parameter to be obtained. Whatever the name is (of course, this must comply with the naming specification of formal parameter variables) eventBus.$on('clickBtn', target => { that.recMsg = target; console.log(target); }); } } </script>
You should be reminded that listening events should be placed in mounted or create.
3) Define the component ChildB and send the "clickBtn" event in ChildB through eventbus to inform the listener to update the data. The code is as follows
<template> <div> <input type="button" v-on:click="addCart" value="Please check the console" /> </div> </template>
<script> import eventBus from '../utils/Bus.js' //Introduce bus js export default { name:'v-childB', data() { return { msg: 'This is B Message sent by component' } }, methods: { addCart(event) { // This clickBtn is a custom event name, this MSG is the data you want to transfer. eventBus.$emit('clickBtn',this.msg); } } } </script>
- Test and create a parent component. The parent component includes v-childA and v-childB components. Click the B component button to display the B component delivery message in component A, and its code is as follows
<template> <div> <v-childA></v-childA> <v-childB></v-childB> </div> </template>
<script> import v-childA from '../components/ v-childA import v-childB from '../components/ v-childB export default { name: "test-event", components: { v-childA, v-childB } } </script>
The operation results are as follows:
Click the button on component B to give the data msg in component B to component A for display.
In fact, eventBus is a typical application of observer mode in design mode. One or more components register the listening event in eventBus, and another component triggers the event and publishes the message.
[note]: two points need to be paid attention to when using bus to transfer data between page components: the function of component v-ChildB
e
m
i
t
matter
piece
answer
stay
b
e
f
o
r
e
D
e
s
t
o
r
y
living
life
week
stage
within
.
his
second
,
group
piece
v
−
c
h
i
l
d
A
within
of
The emit event should be within the beforeDestory life cycle. Secondly, the components in v-childA
The emit event should be within the beforeDestory life cycle. Secondly, the on in the component v − childA is destroyed. It is generally placed in the beforeDestroy() and destroyed() events, and the syntax is eventbus$ The off ('clickBtn ') parameter is the name of the listening event
vuex
VUEX is designed for Vue The state management mode of JS application development adopts centralized storage to manage the state of all components of the application. VUEX implements A one-way data flow and has A state to store data globally. When A component wants to change the data in the state, it must be done through mutation. Mutation also provides A subscriber mode for external plug-ins to call to obtain the update of state data. For example, component A changes msg in state, while components B and C are using msg. VUEX notifies components B and C to modify their state through mutation. VUEX is quite complex, which will be introduced in the following chapters.
sessionStorage and localStorage
The data stored in vuex is in memory, and the page data will be lost when it is refreshed. In some processing scenarios, it is necessary to record the acquired data for A long time, such as login information and token information, which can be used by all components. The solution is to save the state data in localstorage, sessionstorage or cookies. Because of the security of cookies, they are almost no longer used. At this point. Component A writes the data to be communicated to sessionstorage or localstorage in the form of data objects, and component B realizes the communication between components A and B by reading the stored data objects.
localstorage and sessionStorage use key and value for storage. The deposit code is as follows
//Single value storage sessionStorage. setItem('key',value) //The value value must be a string. If it is not a string, it will be automatically converted to a string //Object storage var orderData = { 'orderId': 123, 'price': 88 } sessionStorage.setItem('Cache name', JSON.stringify(orderData)) //Store value: convert object to Json string
Generally, getItem(key) method is used to obtain data. The code is as follows
//Read the single data and obtain the value corresponding to the key sessionStorage.getItem('Key') //Object reading: need to pass JSON Parse() converts text to an object var userJsonStr = sessionStorage.getItem('key'); userEntity = JSON.parse(userJsonStr);
summary
Brother components communicate mainly through bus and vuex. For data that needs to be shared globally, local storage and sessionStorage are used. In component-based development, the communication between components can also be completed through routing and participating slots.