Common methods of Vue componentization: component value transfer and communication

Common methods of Vue componentization: component value transfer and communication

Related knowledge points

  • Passing values ​​from parent component to child component
  • Passing values ​​from child components to parent components
  • Passing values ​​between sibling components
  • Passing values ​​between ancestors and descendants
  • Passing values ​​between any two components

Passing values ​​from parent component to child component

There are three basic methods for passing values ​​from parent components to child components:

  • props
  • References $refs
  • $children

In daily development, we use props and $refs more frequently, and $children less frequently (I have hardly used it~).

props

Add properties in the parent component and receive them in the child component, for example:

Parent component:

<HelloWorld msg="Welcome to Your Vue.js App" />

Subcomponents:

<h1>{{ msg }}</h1>

props: {
 msg: String
}

References $refs

In the parent component, you can use this.$refs.xxx to obtain the data or methods defined in the child component and use them.

Parent component:

<HelloWorld ref="hw" />

mounted() {
 this.$refs.hw.foo = "bar";
}

Subcomponents:

<p>{{ foo }}</p>

data() {
 return {
 foo: "foo"
 };
}

Note:

this.$refs.xxx cannot be used in the created life cycle because the real DOM has not been mounted yet. If you really want to, you can use vm.$nextTick to access the DOM. Or you can understand it this way: the parent component is created before the child component. The child component has not been created during the created lifecycle of the parent component, so the child component cannot be obtained.

In Vue, the component lifecycle calling order is as follows:

The order of calling components is first parent and then child, and the order of rendering is first child and then parent.

The destruction operation of the component is first the parent and then the child, and the order of destruction is first the child and then the parent

Loading the render pass

  • Parent beforeCreate
  • Parent created
  • Parent beforeMount
  • Sub beforeCreate
  • Sub created
  • SubbeforeMount
  • Submounted
  • Parent mounted

Subcomponent update process

  • Parent beforeUpdate
  • SubbeforeUpdate
  • Sub updated
  • Parent updated

Parent component update process

  • Parent beforeUpdate
  • Parent updated

Destruction process

  • Parent beforeDestroy
  • Child beforeDestroy
  • child destroyed
  • Parent destroyed
created() {
 console.log("first execution");
 console.log(this.$refs.hw); // undefined
 this.$nextTick(() => {
 console.log("The third execution");
 console.log(this.$refs.hw); // can be obtained at this time});
}

mounted() {
 console.log("Second execution");
 this.$refs.hw.foo = "bar";
}

$children

Parent component:

this.$children[0].xx = "xxx";

Note:

$children gets the immediate child components of the current instance. If there are multiple child components in a parent component, please note that $children does not guarantee order and is not responsive.

Passing values ​​from child components to parent components

The method used by child components to pass values ​​to parent components is custom events. Dispatched in child components and listened in parent components.

Note: The event listener is the same as the event dispatcher, but it is declared in the parent component.

There are three situations: no parameters, one parameter, and multiple parameters.

No parameters are passed

Subcomponents:

this.$emit('childFoo');

Parent component:

<HelloWorld2 @childFoo="onChildFoo"></HelloWorld2>

methods: {
 onChildFoo() {
 console.log("====== onChildFoo ========");
 }
}

Passing a parameter

Use $event in the parent component to receive parameters.

Subcomponents:

this.$emit('childFooSingle', 'foo');

Parent component:

<HelloWorld2 @childFooSingle="onChildFooSingle($event)"></HelloWorld2>

methods: {
 onChildFooSingle(e) {
 console.log(e); // foo
 }
}

Passing multiple parameters

Use arguments in the parent component to receive parameters, which will be passed in the form of an array.

Subcomponents:

this.$emit('childFooMultiple', 'foo', 'bar', 'dong');

Parent component:

<HelloWorld2 @childFooSingle="onChildFooMultiple(arguments)"></HelloWorld2>

methods: {
 onChildFooMultiple(msg) {
 console.log(msg[0]); // foo
 console.log(msg[1]); // bar
 console.log(msg[2]); // dong
 }
}

Passing values ​​between sibling components

Values ​​can be passed between sibling components through a common parent component, such as $parent and $root.

Brother component 1:

this.$parent.$on('foo', handle);

Brother component 2:

this.$parent.$emit('foo');

Passing values ​​between ancestors and descendants

Since there are too many nested components, it is impractical to pass them using props. Vue provides the provide/inject API to complete this task.

provide/inject enables ancestors to pass values ​​to descendants.

Ancestors:

provide() {
 return {foo: 'foo'}
}

Descendants:

inject: ['foo']

Note: provide and inject mainly provide use cases for high-level components/component libraries. It is not recommended to use them directly in application code. We will see them more often in open source component libraries. However, if you want the descendants to pass on values ​​to the ancestors, this solution will not work! ! !

Official tip: provide and inject bindings are not responsive. This was intentional. However, if you pass in a listenable object, the properties of that object will still be responsive.

Ancestors:

provide() {
 return {
 dong: this.home
 };
},
data() {
 return {
 home: ["App home"]
 };
}

Descendants:

inject: ["dong"]

this.dong = ["App data"]; // Will report an error, Avoid mutating an injected value directly since the changes will be overwritten whenever the provided component re-renders
this.dong.push("App data"); // Can be modified successfully

Passing values ​​between any two components

There are two solutions for passing values ​​between any two components: event bus and Vuex.

Event Bus

Create a Bus class responsible for event dispatching, monitoring, and callback management.

First create a bus.js, import it in main.js, and then use it in the component:

Step 1: Create plugins/bus.js

class Bus{
 constructor(){
 this.callbacks = {}
 }
 $on(name, fn){
 this.callbacks[name] = this.callbacks[name] || []
 this.callbacks[name].push(fn)
 }
 $emit(name, args){
 if (this.callbacks[name]) {
  this.callbacks[name].forEach(cb => cb(args))
 }
 }
}

export default Bus;

Step 2: Import into main.js

import Bus from "./plugins/bus";
Vue.prototype.$bus = new Bus()

Step 3: Use in components

Component 1:

this.$bus.$on('foo', handle)

Component 2:

this.$bus.$emit('foo')

Vuex

Create a unique global data manager store to manage data and notify components of state changes. You can learn about the official document Vuex by yourself first, and I will write a special topic for detailed use later~

Summarize

This concludes this article on the common methods of Vue componentization: component value transfer and communication. For more relevant Vue component value transfer and communication content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Do you know the componentization in Vue life cycle?
  • Vue component learning scoped detailed explanation
  • Essential skills for Vue component development: component recursion
  • Basic usage details of Vue componentization
  • Detailed explanation of component development of Vue drop-down menu
  • Let's learn Vue's componentization together

<<:  Detailed steps to install Docker 1.8 on CentOS 7

>>:  mysql creates root users and ordinary users and modify and delete functions

Recommend

MySql5.7.21 installation points record notes

The downloaded version is the Zip decompression v...

MySQL scheduled task implementation and usage examples

This article uses examples to illustrate the impl...

The whole process record of vue3 recursive component encapsulation

Table of contents Preface 1. Recursive components...

MySQL 5.7.18 MSI Installation Graphics Tutorial

This article shares the MySQL 5.7.18 MSI installa...

Example test MySQL enum type

When developing a project, you will often encount...

js implements shopping cart addition and subtraction and price calculation

This article example shares the specific code of ...

How to operate json fields in MySQL

MySQL 5.7.8 introduced the json field. This type ...

One minute to experience the smoothness of html+vue+element-ui

Technology Fan html web page, you must know vue f...

The linkage method between menu and tab of vue+iview

Vue+iview menu and tab linkage I am currently dev...

Summary of HTML horizontal and vertical centering issues

I have encountered many centering problems recent...

A simple example of MySQL joint table query

MySql uses joined table queries, which may be dif...