Parent-child component communication


1. props

The parent component adds an attribute to the child component :fatherName=”name”, which the child component accepts via props:[‘fatherName’]; The child component can emit events and data to its parent via this.$emit(‘changeFatherName’,’ Daniel Wu ‘), which listens for events and incoming data via @changeFatherName=”changeFatherName”

2. sync/update

V2.3 added syntax sugar, which will be extended to a V-ON listener that updates the binding value of the parent component;


This.$emit(‘update:fatherName’, ‘Daniel Wu ‘) is suitable for passing and modifying basic data types

3. provide/inject

The parent component transmits the value through provide:{fatherAge:30}, the child component receives the value through inject:[“fatherAge”],provide the passed data, not only all the child components can receive, all descendant components can receive by inject

4. $attrs/$listeners

V2.4 new

$attrs contains property bindings (except class and style) that are not recognized (and retrieved) as prop in the parent scope. For example, Father passed fatherName components, fatherAge, fatherJob three properties And child components only by props received fatherName child components will default to render the < div fatherage = “30” Fatherjob =”engineer”>, inheritAttrs:false can prevent this default behavior, and inheritAttrs can pass these attributes to grandchildren via v-bind=”$attrs”, FatherAge =”$attrs.fatherAge” :fatherJob=”$attrs.fatherJob”

The $Listeners contain V-ON event listeners in the parent scope (without the.native modifier), $Listeners can pass the parent’s changeFatherName event to the grandparent via v-on=”$Listeners “, allowing the grandparent to modify its data across levels

5. $children/$parent

This.$children[0]. Age =2; this.$parent. Age =30

6. ref/refs

$this.$refs[‘ XXX ‘]; $this.$refs[‘son’]===this.$children[0] //true

< / / parent component template > < div > < h3 > dad: < / h3 > < div > name: {{name}} < / div > < div > age: </div> <button @click="seeSon"> </button> <son :fatherName="name" :fatherAge="age" :fatherJob="job" @changeFatherName="changeFatherName" ref="son" ></son> <! -- <son :fatherName.sync="name" ref="son"></son> --> </div> </template> <script> import son from './son.vue' export default { components: { son, }, provide:{ fatherAge:30 }, data() { return { name:'father', age:30, job:'engineer' } }, Methods :{seeSon(){console.log(this.$refs['son']===this.$children[0]) //true this console.log(this.$children[0].age) //1 = 2 }, changeFatherName(val){ this.name=val } } } </script>Copy the code
// Child <template> <div> <h3>{{' son: my father is ${fatherName}; This year ` age of ${fatherAge}}} < / h3 > < div > name: {{name}} < / div > < div > age: {{age}}</div> < button@click ="seeFather" </button> <grandson v-bind="$attrs" v-on="$listeners"></grandson> </div> </template> <script> import grandson from './grandson.vue' export default { components: { grandson, }, props: ['fatherName'], inject: ['fatherAge'], inheritAttrs:false, data() { return { name:'baby', age:1 } }, methods:{ seeFather(){ console.log(this.$parent.age) //30 }, ChangeFatherName () {this.$emit('changeFatherName',' thu ')}}, created(){ console.log(this.$attrs) // { "fatherAge": "30", "fatherJob": "engineer" } } } </script>Copy the code
<template> <div> <h3>{{' grandchild: ${fatherAge}; Is a ${fatherJob}; </h3> <button @click="changeFatherName" > </button> </div> </template> <script> export default {props: ['fatherJob'], inject: ['fatherAge'], inheritAttrs:false, methods:{setname () {this.$emit(' setname ',' setname ')},}, created(){ console.log(this.$attrs) // { "fatherAge": "30" } } } </script>Copy the code

7. Modify subcomponents directlyprops/injectThe value passed in

  • ifpropsisBasic data typesProp changes in the child component, does not change in the parent component and the console reports an error
  • ifpropsisReference data type, both parent and child components will be successfully modified without error (not recommended)

Data transfer between non-parent and sibling components


Vuex

Please refer to the official document vuex.vuejs.org/zh/ to add a Vuex principle, and then arrange in detail 😄

EventBus

EventBus, also known as the eventBus, can be used in vue as a bridge concept, as if all components share the same event center to which they can register to send and receive events, and all components can notify other components. (Difficult to maintain, difficult to name eventName, not easy to maintain, not timely cancellation of events will cause various problems, complex projects still use Vuex)

// create a Vue instance as the central EventBus let EventBus = new Vue(); / / to monitor events EventBus. $on (' eventName '(val) = > {/ /... do something }); $emit('eventName', 'this is a message.'); $off('eventName', {})Copy the code

localStorage/sessionStorage

Local storage, some business use is more, such as user tocken system Settings window. The localStorage. The getItem (key) to get the data, through the window. The localStorage. SetItem (key, value) stored data; Note: Value can only be a string value, the same as sessionStorage conversion with json.parse ()/json.stringify ()

conclusion


  • Parent-child component communication: props; . The sync/update; provide/inject ; $parent/$children; ref/refs; $attrs/$listeners

  • Non-parent/sibling communication: EventBus; Vuex; localStorage/sessionStorage