Home Web Front-end JS Tutorial Vue component communication (detailed tutorial)

Vue component communication (detailed tutorial)

Jun 07, 2018 am 11:52 AM
vue vue component communication components

This article mainly introduces you to four methods of Vue component communication, namely parent-child component communication, non-parent-child component eventBus communication, using localStorage or sessionStorage, and using Vuex. Friends in need can refer to it. Let’s study together below.

Preface

As we all know, vue is a mvvm framework. One of its biggest differences compared to jquery is that between components of communication. The focus of this article is to sort out the first two, parent-child component communication and eventBus communication. I think the instructions in the Vue document are still a bit simple, and I didn't understand them the first time.

  • Communication of parent-child components

  • EventBus communication of non-parent-child components

  • Use local cache to implement Component communication

  • Vuex communication

##The first communication method: parent-child component communication

Parent component passes data to child component

The parent component needs to do 4 things in total

1.

import son from './son .js' Introduce the sub-component son

2. Register all sub-component names in

components: {"son"}

3. In the parent component template applies sub-component,

4. If you need to pass data to the sub-component, write

 // 1.引入子组件 
 import counter from './counter'
 import son from './son'
Copy after login
// 2.在ccmponents里注册子组件
 components : {
 counter,
 son
 },
Copy after login
// 3.在template里使用子组件
 <son></son>
Copy after login
 // 4.如果需要传递数据,也是在templete里写
 <counter :num="number"></counter>
Copy after login

The sub-component only needs to do one thing

1. Use props to accept data, and you can use the data directly

2. The data received by the sub-component cannot be modified. If you really need to modify it, you can use calculated properties, or assign the data to a variable in the child component data

 // 1.用Props接受数据
 props: [
  &#39;num&#39;
  ],
Copy after login
// 2.如果需要修改得到的数据,可以这样写
 props: [
  &#39;num&#39;
 ],
 data () {
 return {
  number : this.num
 }
 },
Copy after login

The child component passes data to the parent component

Parent The component needs to do a total of 2 things

Define the event in the template

Write a function in methods to monitor the event triggering of the sub-component

// 1. 在templete里应用子组件时,定义事件changeNumber
 <counter :num="number"
   @changeNumber="changeNumber"
 >
 </counter>
Copy after login
// 2. 用changeNumber监听事件是否触发
 methods: {
  changeNumber(e){
  console.log(&#39;子组件emit了&#39;,e);
  this.number = e
  },
 }
Copy after login

The sub-component needs a total of 1 thing

After the data changes, use $emit to trigger it

// 1. 子组件在数据变化后,用$emit触发即可,第二个参数可以传递参数
 methods: {
  increment(){
   this.number++
   this.$emit(&#39;changeNumber&#39;, this.number)
  },
 }
Copy after login

Second communication method: eventBus##eventBus This communication method is aimed at communication between non-parent and child components. Its principle is still through event triggering and monitoring.

But because they are non-parent-child components, they need an intermediate component to connect.

I use it by defining a component that can be accessed by all components on the root component, which is the #app component. The specific usage is as follows

Using eventBus to pass data, we have a total of Three things need to be done

1. Add the Bus attribute to the app component (so that all components can access it through

this.$root.Bus

, and there is no need to introduce any files) 2. In component 1,

this.$root.Bus.$emit

triggers the event 3. In component 2,

this.$root. Bus.$on

Listening events<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>// 1.在main.js里给app组件,添加bus属性 import Vue from &amp;#39;vue&amp;#39; new Vue({ el: &amp;#39;#app&amp;#39;, components: { App }, template: &amp;#39;&lt;App/&gt;&amp;#39;, data(){ return { Bus : new Vue() } } })</pre><div class="contentsignin">Copy after login</div></div><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>// 2.在组件1里,触发emit increment(){ this.number++ this.$root.Bus.$emit(&amp;#39;eventName&amp;#39;, this.number) },</pre><div class="contentsignin">Copy after login</div></div><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>// 3.在组件2里,监听事件,接受数据 mounted(){ this.$root.Bus.$on(&amp;#39;eventName&amp;#39;, value =&gt; { this.number = value console.log(&amp;#39;busEvent&amp;#39;); }) },</pre><div class="contentsignin">Copy after login</div></div></p> <p>The third communication method: using localStorage or sessionStorage<span style="color: #ff0000"><strong></strong></span>This communication is relatively simple, The disadvantage is that the data and status are chaotic and not easy to maintain. </p> <p>Pass </p>window.localStorage.getItem(key) <p>Get data<code>Pass

window.localStorage.setItem(key,value)

Store data

Note: Use JSON.parse() / JSON.stringify() for data format conversion.

The fourth communication method: using VuexVuex is more complicated, you can write a separate article

The above is me I compiled it for everyone, I hope it will be helpful to everyone in the future.

Related articles:

Use SpringMVC to solve vue cross-domain requests

New features of webpack 4.0.0-beta.0 version (details Tutorial)

How to implement value passing and communication in vue2.0 components

The above is the detailed content of Vue component communication (detailed tutorial). 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)

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 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.

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.

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 jump to the div of vue How to jump to the div of vue Apr 08, 2025 am 09:18 AM

There are two ways to jump div elements in Vue: use Vue Router and add router-link component. Add the @click event listener and call this.$router.push() method to jump.

See all articles