Home  >  Article  >  Web Front-end  >  What are the ways to communicate between Vue components?

What are the ways to communicate between Vue components?

WBOY
WBOYOriginal
2022-03-24 17:41:1717855browse

Method: 1. Communicate through common ancestor "$parent" or "$root"; 2. Parent component communicates by setting child component ref; 3. Brother component triggers customization through "$emit" Event, the second parameter of "$emit" is the passed value, and another sibling component listens to the custom event through "$on".

What are the ways to communicate between Vue components?

The operating environment of this article: Windows 10 system, Vue version 2.9.6, DELL G3 computer.

What are the ways of communication between Vue components

1. The concept of communication between components

Before we start, we put the components Split the word communication between

Component

Communication

We all know that components are one of the most powerful functions of vue. We can view every .vue in vue It is a component

Communication refers to the sender transmitting information to the recipient through a certain media and a certain format to achieve a certain purpose. In a broad sense, any information traffic is communication

Inter-component communication means that components (.vue) pass information in a certain way to achieve a certain purpose

For example

When we use the table component in the UI framework, we may pass some data into the table component. This essentially forms the communication between components.

2. Components What does inter-communication solve?

In ancient times, people transmitted information through inns, flying pigeons, beacon fire alarms, symbols, language, eyes, touch, etc. Today, anytime With the rapid development of science and technology, communication is basically completed by wired or wireless. Various communication methods such as wired telephones, landline telephones, wireless telephones, mobile phones, the Internet and even video calls have appeared one after another.

From the above paragraph , we can see that the essence of communication is information synchronization and sharing

Back to vue, each component has its own scope, and the data between components cannot be shared

But in actual development work, we often need to let components share data, which is also the purpose of component communication

To allow them to communicate with each other, in order to form an organic and complete system

2. Classification of communication between components

The classification of communication between components can be divided into the following

  • Father and child components Communication between components

  • Communication between sibling components

  • Communication between ancestors and descendants

  • Communication between non-relational components

3. Communication plan between components

Organization 8 common communication solutions in vue

  • Transmitted through props

  • Triggered custom events through $emit

  • Use ref

  • EventBus

  • parent or root

  • attrs and listeners

  • Provide and Inject

  • Vuex

props pass data

Applicable scenarios: parent component passes data to child component

The child component sets the props attribute and defines the parameters to be received from the parent component

The parent component uses the literal when using the child component tag To pass the value

Children.vue

props:{
    // 字符串形式
 name:String // 接收的类型参数
    // 对象形式
    age:{  
        type:Number, // 接收的类型为数值
        defaule:18,  // 默认值为18
       require:true // age属性必须传递
    }
}

Father.vue component

e9228173091c43112296baf114d9d5af

$emit triggers custom events

Applicable scenarios: child components pass data to parent components

The child components trigger custom events through $emit, the second parameter of $emit Bind the listener to the passed value

The parent component gets the parameters passed from the child component

Chilfen.vue

this.$emit('add', good)
Father.vue
<Children @add="cartAdd($event)" />

ref

The parent component sets ref when using the child component

The parent component obtains data by setting the child component ref

Parent component

<Children ref="foo" />
this.$refs.foo  // 获取子组件实例,通过子组件实例我们就能拿到对应的数据

EventBus

Usage scenario: brother component passes value

Create a central time bus EventBus

The brother component triggers a custom event through $emit, and the second parameter of $emit is passed The value

Another sibling component listens to the custom event through $on

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));
    }
  }
}
// main.js
Vue.prototype.$bus = new Bus() // 将$bus挂载到vue实例的原型上
// 另一种方式
Vue.prototype.$bus = new Vue() // Vue已经实现了Bus的功能
Children1.vue
this.$bus.$emit(&#39;foo&#39;)
Children2.vue
this.$bus.$on(&#39;foo&#39;, this.handle)

Parent or root

Build a communication overseas association through the common ancestor $parent or $root

Brother component

this.$parent.on(&#39;add&#39;,this.add)

Another brother component

this.$parent.emit(&#39;add&#39;)

attrs and listeners

Applicable scenarios: Ancestors pass data to descendants

Set batch upload attributes $attrs and $listeners

Includes properties in the parent scope that are not recognized (and obtained) as props Property binding (except class and style).

You can pass v-bind="$attrs" to pass in internal components

// child:并未在props中声明foo
<p>{{$attrs.foo}}</p>
// parent
<HelloWorld foo="foo"/>
// 给Grandson隔代传值,communication/index.vue
<Child2 msg="lalala" @some-event="onSomeEvent"></Child2>
// Child2做展开
<Grandson v-bind="$attrs" v-on="$listeners"></Grandson>
// Grandson使⽤
<div @click="$emit(&#39;some-event&#39;, &#39;msg from grandson&#39;)">
{{msg}}
</div>

provide and inject

define the provide attribute in the ancestor component and return The passed value

The descendant component receives the value passed by the component through inject

Ancestor component

provide(){
    return {
        foo:&#39;foo&#39;
    }
}

Descendant component

inject:['foo'] // Get the value passed from the ancestor component

vuex

Applicable scenarios: Component data transfer with complex relationships

Vuex is equivalent to a container used to store shared variables

state is used to store shared variables

getter, you can add a getter derived state, (equivalent to the store) Computed attributes), used to obtain the value of shared variables

mutations are used to store methods for modifying state.

Actions are also used to store methods for modifying state, but actions are based on mutations. Commonly used to do some asynchronous operations

Summary

For the component data transfer of the parent-child relationship, props and $emit can be selected for transfer, or you can choose ref

The component data transfer of the sibling relationship can be Select $bus, and then you can select $parent for transfer

For ancestor and descendant component data transfer, you can choose attrs and listeners or Provide and Inject

For complex relationship component data transfer, you can store shared data through vuex Variable

[Related recommendation: "vue.js tutorial"]

The above is the detailed content of What are the ways to communicate between Vue components?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn