Table of Contents
What are the ways of communication between Vue components
Home Web Front-end Vue.js What are the ways to communicate between Vue components?

What are the ways to communicate between Vue components?

Mar 24, 2022 pm 05:41 PM
vue

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属性必须传递
    }
}
Copy after login

Father.vue component

$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)" />
Copy after login

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  // 获取子组件实例,通过子组件实例我们就能拿到对应的数据
Copy after login

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

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)
Copy after login

Another brother component

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

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"/>
Copy after login
// 给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>
Copy after login

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;
    }
}
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1263
29
C# Tutorial
1237
24
How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

How to add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

How to use watch in vue How to use watch in vue Apr 07, 2025 pm 11:36 PM

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

What does vue multi-page development mean? What does vue multi-page development mean? Apr 07, 2025 pm 11:57 PM

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

How to return to previous page by vue How to return to previous page by vue Apr 07, 2025 pm 11:30 PM

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses &lt;router-link to=&quot;/&quot; component window.history.back(), and the method selection depends on the scene.

React vs. Vue: Which Framework Does Netflix Use? React vs. Vue: Which Framework Does Netflix Use? Apr 14, 2025 am 12:19 AM

Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

How to use vue traversal How to use vue traversal Apr 07, 2025 pm 11:48 PM

There are three common methods for Vue.js to traverse arrays and objects: the v-for directive is used to traverse each element and render templates; the v-bind directive can be used with v-for to dynamically set attribute values ​​for each element; and the .map method can convert array elements into new arrays.

How to reference js file with vue.js How to reference js file with vue.js Apr 07, 2025 pm 11:27 PM

There are three ways to refer to JS files in Vue.js: directly specify the path using the &lt;script&gt; tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

See all articles