Communication mode between vue components (full)

Component communication classification:

  1. Parent child component communication
  2. Sibling component communication
  3. Grandson and descendant component communication‘
  4. Non relational component communication

8 common communication modes

1. Pass through props

Usage scenario: parent to child
Usage: the child component sets and declares the props attribute and defines the parameters passed by the receiving parent component; The parent component passes the value by literal in the label of the child component

//Sub assembly child vue
//Define receiving parameters
props:{
	name:String; //String type
	age:{		//object type
		type:Number,
		default:18,		//Default value
		require:true //Indicates that the parent component must pass the age parameter
	}
}
//Parent component uses child component
<Child name="Zhang San" age=20/>

Title 2$ Emit triggers a custom event

Usage scenario: pass from child to parent
Usage: the sub component triggers a user-defined event through $emit and passes the value; The parent component binding listener gets the value passed by the child component

//Sub assembly child vue
<input @click="onClick"/>  	//Set custom events
...
methods:{
	onClick(){
		this.$emit('toValue',"Value passed")
	}
}

//Parent component
<Child @toValue="getValue"/>	//One value can be passed without parameters, and multiple values must be passed with parameters
...
data(){
	return{
		value:'',
	}
}
methods:{
	getValue(value){
		this.value = value;	//When passing multiple values, the value at this time is an array
	}
}

3. ref

Usage scenario: parent takes child value
Usage method: the parent component sets ref when using child components; The parent component obtains data by setting the sub component ref; Then you can change the attribute value of the child component through ref in the parent component

//Sub assembly child vue
data(){
	return:{
		value:"I am the value in the subcomponent"
	}
},
methods:{
	setValue(){
		console.log("I am the method in the subcomponent");
	}
}
//Parent component
<Child ref="foo"/>
<button @click="getValue"/>
...
methods:{
	getValue(){
		console.log(this.$refs.foo.value);	//The output is the value in the subcomponent
		console.log(this.$refs.foo.setValue());	//Output is the method in the subcomponent
	}
}

4. evenBus

Usage scenario: sibling component value transfer
Usage: create a central event bus eventBus separately, and a new instance of a vue, which is similar to a station and connected with two components; Sibling components start custom events and pass parameters through $emit; Another component listens to custom events through $on

//eventBus.js 
//Create a bus instance
import Vue from 'Vue'
export default new Vue
// Brother component 1 brother vue
<input @click="onClick"/>  	//Set custom events
...

// Introducing bus
import bus from '../assets/eventBus'
export default{
	methods:{
		onClick(){
			this.$emit('toValue',"Value passed")
		}
	}
}

//Brother assembly 2 
<p>Information received from brother component 1:{{msg}}</p>
...
//Introducing bus
import bus from '../assets/eventBus'

data(){
	return{
		msg:'Default value',
	}
},
mounted(){
	var that = this;
	//Listen for custom events via $on
	bus.$on("toValue",function(msg){
		that.msg = msg;
	})
}

5.$parent,$children

Usage scenario: parent to child, child to parent
Usage: directly use $parent and $children in the child component and parent component respectively to obtain the data of the other party
For example, $children is used in the same way

//Sub assembly child vue
//Define receiving parameters
data(){
	return{
		name:"Zhang San";
	}
},
methods:{
	setValue(){
		console.log("I am the method in the subcomponent");
	}
}
//Parent component uses child component
<Child />
...
mounted () {
  // Get all the sub components, and the result is an array
  console.log(this.$children)
  // Gets the specified data in the specified subcomponent
  console.log(this.$children[0].value)
  // Method of calling subcomponent
  this.$children[0].setValue()
}

6.$attrs and $listeners

Usage scenario: the group transfers data to its descendants first
Usage: set the batch download attributes $attrs and $listeners;
$attrs contains attribute bindings that are not recognized as props in the parent scope: v-bind="$attrs" bind all non props attributes to corresponding tags;
Method binding subcomponents on all components can receive through $listeners: v-on="$listeners" bind all methods to the corresponding tags of the component

7.project and project

Usage scenario: ancestors pass data to offspring
Usage: define the project attribute in the group component first and return the passed value; Receive the passed value through inject in the descendant component

//Ancestor component. Define the provide attribute in the ancestor component and return the passed value
provide(){
    return{
        value:'I am the value in the ancestor component',
    }
}
//The descendant component receives the value passed by the component through inject in the descendant component
inject:['value'] 

8.vuex

Usage scenario: component data transfer with complex relationships
Vuex acts as a container for storing shared variables
Usage:
state: the place where shared variables are stored
getter: used to get the value of the shared variable
Changes: used to store the method of modifying state
actions: it is used to store the method of modifying state, but action s usually do some asynchronous operations.

summary

Component data transfer type, optional methods:

  1. Parent child relationship: propos e (from parent to child), $emit (from child to parent), ref (from parent to child)
  2. Brotherhood: $eventBus p a r e n t ( through too common with Ancestor Generation parent (through common ancestor) parent (build communication bridge through common grandparents)
  3. Ancestors and descendants: $attrs and $listeners, project and inject
  4. Complex relationships: Vuex

If this article is helpful to you, leave a praise 👍 Come on!

Keywords: Javascript Vue Vue.js

Added by wolfrat on Sun, 20 Feb 2022 00:24:22 +0200