search
HomeWeb Front-endVue.jsHow to communicate between Vue components? Brief analysis of six methods

How to communicate between Vue components? Brief analysis of six methods

Mar 22, 2023 pm 04:54 PM
front endvue.jsComponent communication

How to communicate between Vue components? The following article will introduce you to the six ways of Vue component communication. I hope it will be helpful to you!

How to communicate between Vue components? Brief analysis of six methods

Components are one of the most powerful features of vue.js, and the scopes of component instances are independent of each other, which means that data between different components cannot Cross-referencing. Generally speaking, components can have several relationships.

How to choose an effective communication method for different usage scenarios? This is the topic we are going to explore. This article summarizes several ways of communication between Vue components, such as props, emit/emit/on, vuex, parent/parent/children, attrs/attrs/listeners and provide/inject, and explains the differences with easy-to-understand examples. and usage scenarios, I hope it can be of some help to my friends. [Related recommendations: vuejs video tutorial, web front-end development]

Method 1, props/$emit

The way parent component A passes props Passing to sub-component B, B to A is achieved by $emit in component B and v-on in component A.

1. Parent component passes value to child component

Next we use an example to illustrate how the parent component passes value to child component: in the child component Users.vue How to get the data in the parent component App.vue users:["Henry","Bucky","Emily"]

//App.vue父组件
<template>
  <div id="app">
    <users v-bind:users="users"></users>//前者自定义名称便于子组件调用,后者要传递数据名
  </div>
</template>
<script>
import Users from "./components/Users"
export default {
  name: &#39;App&#39;,
  data(){
    return{
      users:["Henry","Bucky","Emily"]
    }
  },
  components:{
    "users":Users
  }
}
//users子组件
<template>
  <div class="hello">
    <ul>
      <li v-for="user in users">{{user}}</li>//遍历传递过来的值,然后呈现到页面
    </ul>
  </div>
</template>
<script>
export default {
  name: &#39;HelloWorld&#39;,
  props:{
    users:{           //这个就是父组件中子标签自定义名字
      type:Array,
      required:true
    }
  }
}
</script>

Summary: The parent component passes data downward to the child component through props. Note: There are three forms of data in the component: data, props, computed

2. Child components pass values ​​to parent components (through events)

Next, we use an example to illustrate how the sub-component passes a value to the parent component: when we click "Vue.js Demo", the sub-component passes a value to the parent component, and the text changes from the original "A value is passed" to "Child passes value to parent component" to realize the transfer of value from child component to parent component.

// 子组件
<template>
  <header>
    <h1 id="title">{{title}}</h1>//绑定一个点击事件
  </header>
</template>
<script>
export default {
  name: &#39;app-header&#39;,
  data() {
    return {
      title:"Vue.js Demo"
    }
  },
  methods:{
    changeTitle() {
      this.$emit("titleChanged","子向父组件传值");//自定义事件  传递值“子向父组件传值”
    }
  }
}
</script>
// 父组件
<template>
  <div id="app">
    <app-header v-on:titleChanged="updateTitle" ></app-header>//与子组件titleChanged自定义事件保持一致
   // updateTitle($event)接受传递过来的文字
    <h2 id="title">{{title}}</h2>
  </div>
</template>
<script>
import Header from "./components/Header"
export default {
  name: &#39;App&#39;,
  data(){
    return{
      title:"传递的是一个值"
    }
  },
  methods:{
    updateTitle(e){   //声明这个函数
      this.title = e;
    }
  },
  components:{
   "app-header":Header,
  }
}
</script>

Summary: The child component sends messages to the parent component through events. In fact, the child component sends its own data to the parent component.

Method 2, $emit/$on

This method passes an empty The Vue instance serves as the central event bus (event center), using it to trigger events and listen for events, cleverly and lightweightly realizing communication between any components, including parent-child, brother, and cross-level . When our project is relatively large, we can choose vuex, a better state management solution.

1. Specific implementation method:

    var Event=new Vue();
    Event.$emit(事件名,数据);
    Event.$on(事件名,data => {});

2. For example

Assume that there are three sibling components, namely A, B, and C components. How does C component obtain A? Or the data of component B

<div id="itany">
	<my-a></my-a>
	<my-b></my-b>
	<my-c></my-c>
</div>
<template id="a">
  <div>
    <h3 id="A组件-name">A组件:{{name}}</h3>
    <button @click="send">将数据发送给C组件</button>
  </div>
</template>
<template id="b">
  <div>
    <h3 id="B组件-age">B组件:{{age}}</h3>
    <button @click="send">将数组发送给C组件</button>
  </div>
</template>
<template id="c">
  <div>
    <h3 id="C组件-name-age">C组件:{{name}},{{age}}</h3>
  </div>
</template>
<script>
var Event = new Vue();//定义一个空的Vue实例
var A = {
	template: &#39;#a&#39;,
	data() {
	  return {
	    name: &#39;tom&#39;
	  }
	},
	methods: {
	  send() {
	    Event.$emit(&#39;data-a&#39;, this.name);
	  }
	}
}
var B = {
	template: &#39;#b&#39;,
	data() {
	  return {
	    age: 20
	  }
	},
	methods: {
	  send() {
	    Event.$emit(&#39;data-b&#39;, this.age);
	  }
	}
}
var C = {
	template: &#39;#c&#39;,
	data() {
	  return {
	    name: &#39;&#39;,
	    age: ""
	  }
	},
	mounted() {//在模板编译完成后执行
	Event.$on(&#39;data-a&#39;,name => {
	     this.name = name;//箭头函数内部不会产生新的this,这边如果不用=>,this指代Event
	})
	Event.$on(&#39;data-b&#39;,age => {
	     this.age = age;
	})
	}
}
var vm = new Vue({
	el: &#39;#itany&#39;,
	components: {
	  &#39;my-a&#39;: A,
	  &#39;my-b&#39;: B,
	  &#39;my-c&#39;: C
	}
});	
</script>

$on listens to the custom events data-a and data-b, because sometimes it is not sure when the event will be triggered, usually in the mounted or created hook Come in to monitor.

Method 3, vuex

How to communicate between Vue components? Brief analysis of six methods

1. Briefly introduce the principle of Vuex Vuex implements a one-way data flow and has a State to store data globally. When a component wants to change the data in the State, it must be done through Mutation. Mutation also provides a subscriber mode for external plug-ins to call to obtain updates to the State data. When all asynchronous operations (commonly called back-end interfaces are used to obtain update data asynchronously) or batch synchronous operations require Action, Action cannot directly modify State. State data still needs to be modified through Mutation. Finally, based on the changes in State, it is rendered to the view.

2.简要介绍各模块在流程中的功能: Vue Components:Vue组件。HTML页面上,负责接收用户操作等交互行为,执行dispatch方法触发对应action进行回应。 dispatch:操作行为触发方法,是唯一能执行action的方法。 actions:操作行为处理模块,由组件中的$store.dispatch('action 名称', data1)来触发。然后由commit()来触发mutation的调用 , 间接更新 state。负责处理Vue Components接收到的所有交互行为。包含同步/异步操作,支持多个同名方法,按照注册的顺序依次触发。向后台API请求的操作就在这个模块中进行,包括触发其他action以及提交mutation的操作。该模块提供了Promise的封装,以支持action的链式触发。 commit:状态改变提交操作方法。对mutation进行提交,是唯一能执行mutation的方法。 mutations:状态改变操作方法,由actions中的commit('mutation 名称')来触发。是Vuex修改state的唯一推荐方法。该方法只能进行同步操作,且方法名只能全局唯一。操作之中会有一些hook暴露出来,以进行state的监控等。 state:页面状态管理容器对象。集中存储Vue components中data对象的零散数据,全局唯一,以进行统一的状态管理。页面显示所需的数据从该对象中进行读取,利用Vue的细粒度数据响应机制来进行高效的状态更新。 getters:state对象读取方法。图中没有单独列出该模块,应该被包含在了render中,Vue Components通过该方法读取全局state对象。 3.Vuex与localStorage vuex 是 vue 的状态管理器,存储的数据是响应式的。但是并不会保存起来,刷新之后就回到了初始状态,具体做法应该在vuex里数据改变的时候把数据拷贝一份保存到localStorage里面,刷新之后,如果localStorage里有保存的数据,取出来再替换store里的state。

let defaultCity = "上海"
try {   // 用户关闭了本地存储功能,此时在外层加个try...catch
  if (!defaultCity){
    defaultCity = JSON.parse(window.localStorage.getItem(&#39;defaultCity&#39;))
  }
}catch(e){}
export default new Vuex.Store({
  state: {
    city: defaultCity
  },
  mutations: {
    changeCity(state, city) {
      state.city = city
      try {
      window.localStorage.setItem(&#39;defaultCity&#39;, JSON.stringify(state.city));
      // 数据改变的时候把数据拷贝一份保存到localStorage里面
      } catch (e) {}
    }
  }
})

这里需要注意的是:由于vuex里,我们保存的状态,都是数组,而localStorage只支持字符串,所以需要用JSON转换:

JSON.stringify(state.subscribeList);   // array -> string
JSON.parse(window.localStorage.getItem("subscribeList"));    // string -> array 
复制代码

方法四、attrs/attrs/listeners

1.简介

多级组件嵌套需要传递数据时,通常使用的方法是通过vuex。但如果仅仅是传递数据,而不做中间处理,使用 vuex 处理,未免有点大材小用。为此Vue2.4 版本提供了另一种方法----attrs/attrs/listeners

##attrs: Contains items not included in the parent scope that are propIdentified ( and obtained the property binding of )(class and styleexcept ). When a component does not declare any prop, all parent scopes will be included here Binding (class and styleexcept ) , and can be passed vbind ="attrs: Contains attribute bindings (except class and style) in the parent scope that are not recognized (and obtained) by prop. When a When the component does not declare any props, all parent scope bindings (except class and style) will be included here, and can be passed v-bind="

listeners:包含了父作用域中的(不含.native修饰器的)von事件监听器。它可以通过von="listeners:包含了父作用域中的 (不含 .native 修饰器的) v-on 事件监听器。它可以通过 v-on="listeners" 传入内部组件

接下来我们看个跨级通信的例子:

// index.vue
<template>
  <div>
    <h2 id="浪里行舟">浪里行舟</h2>
    <child-com1
      :foo="foo"
      :boo="boo"
      :coo="coo"
      :doo="doo"
      title="前端工匠"
    ></child-com1>
  </div>
</template>
<script>
const childCom1 = () => import("./childCom1.vue");
export default {
  components: { childCom1 },
  data() {
    return {
      foo: "Javascript",
      boo: "Html",
      coo: "CSS",
      doo: "Vue"
    };
  }
};
</script>
// childCom1.vue
<template class="border">
  <div>
    <p>foo: {{ foo }}</p>
    <p>childCom1的$attrs: {{ $attrs }}</p>
    <child-com2 v-bind="$attrs"></child-com2>
  </div>
</template>
<script>
const childCom2 = () => import("./childCom2.vue");
export default {
  components: {
    childCom2
  },
  inheritAttrs: false, // 可以关闭自动挂载到组件根元素上的没有在props声明的属性
  props: {
    foo: String // foo作为props属性绑定
  },
  created() {
    console.log(this.$attrs); // { "boo": "Html", "coo": "CSS", "doo": "Vue", "title": "前端工匠" }
  }
};
</script>
// childCom2.vue
<template>
  <div class="border">
    <p>boo: {{ boo }}</p>
    <p>childCom2: {{ $attrs }}</p>
    <child-com3 v-bind="$attrs"></child-com3>
  </div>
</template>
<script>
const childCom3 = () => import("./childCom3.vue");
export default {
  components: {
    childCom3
  },
  inheritAttrs: false,
  props: {
    boo: String
  },
  created() {
    console.log(this.$attrs); // { "coo": "CSS", "doo": "Vue", "title": "前端工匠" }
  }
};
</script>
// childCom3.vue
<template>
  <div class="border">
    <p>childCom3: {{ $attrs }}</p>
  </div>
</template>
<script>
export default {
  props: {
    coo: String,
    title: String
  }
};
</script>

How to communicate between Vue components? Brief analysis of six methods

如上图所示attrs表示没有继承数据的对象,格式为属性名:属性值。Vue2.4提供了attrs表示没有继承数据的对象,格式为{属性名:属性值}。Vue2.4提供了attrs , $listeners 来传递数据与事件,跨级组件之间的通讯变得更简单。

简单来说:attrsattrs与listeners 是两个对象,attrs里存放的是父组件中绑定的非Props属性,attrs 里存放的是父组件中绑定的非 Props 属性,listeners里存放的是父组件中绑定的非原生事件。

方法五、provide/inject

1.简介

Vue2.2.0新增API,这对选项需要一起使用,以允许一个祖先组件向其所有子孙后代注入一个依赖,不论组件层次有多深,并在起上下游关系成立的时间里始终生效。一言而蔽之:祖先组件中通过provider来提供变量,然后在子孙组件中通过inject来注入变量。 provide / inject API 主要解决了跨级组件间的通信问题,不过它的使用场景,主要是子组件获取上级组件的状态,跨级组件间建立了一种主动提供与依赖注入的关系。

2.举个例子

假设有两个组件: A.vue 和 B.vue,B 是 A 的子组件

// A.vue
export default {
  provide: {
    name: &#39;浪里行舟&#39;
  }
}
// B.vuee
xport default {
  inject: [&#39;name&#39;],  mounted () {
    console.log(this.name);  // 浪里行舟
  }
}

可以看到,在 A.vue 里,我们设置了一个 provide: name,值为 浪里行舟,它的作用就是将 name 这个变量提供给它的所有子组件。而在 B.vue 中,通过 inject 注入了从 A 组件中提供的 name 变量,那么在组件 B 中,就可以直接通过 this.name 访问这个变量了,它的值也是 浪里行舟。这就是 provide / inject API 最核心的用法。

需要注意的是:provide 和 inject 绑定并不是可响应的。这是刻意为之的。然而,如果你传入了一个可监听的对象,那么其对象的属性还是可响应的----vue官方文档 所以,上面 A.vue 的 name 如果改变了,B.vue 的 this.name 是不会改变的,仍然是 浪里行舟。

方法六、parent/parent /children与 ref

ref:如果在普通的 DOM 元素上使用,引用指向的就是 DOM 元素;如果用在子组件上,引用就指向组件实例parent/parent /children:访问父 / 子实例 需要注意的是:这两种都是直接得到组件实例,使用后可以直接调用组件的方法或访问数据。我们先来看个用 ref来访问组件的例子

// component-a 子组件
export default {
  data () {
    return {
      title: &#39;Vue.js&#39;
    }
  },
  methods: {
    sayHello () {
      window.alert(&#39;Hello&#39;);
    }
  }
}
// 父组件
<template>
  <component-a ref="comA"></component-a>
</template>
<script>
  export default {
    mounted () {
      const comA = this.$refs.comA;
      console.log(comA.title);  // Vue.js
      comA.sayHello();  // 弹窗
    }
  }
</script>
复制代码

不过,这两种方法的弊端是,无法在跨级或兄弟间通信

(学习视频分享:vuejs入门教程编程基础视频

The above is the detailed content of How to communicate between Vue components? Brief analysis of six methods. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
Vue.js and the Frontend: A Deep Dive into the FrameworkVue.js and the Frontend: A Deep Dive into the FrameworkApr 22, 2025 am 12:04 AM

Vue.js is loved by developers because it is easy to use and powerful. 1) Its responsive data binding system automatically updates the view. 2) The component system improves the reusability and maintainability of the code. 3) Computing properties and listeners enhance the readability and performance of the code. 4) Using VueDevtools and checking for console errors are common debugging techniques. 5) Performance optimization includes the use of key attributes, computed attributes and keep-alive components. 6) Best practices include clear component naming, the use of single-file components and the rational use of life cycle hooks.

The Power of Vue.js on the Frontend: Key Features and BenefitsThe Power of Vue.js on the Frontend: Key Features and BenefitsApr 21, 2025 am 12:07 AM

Vue.js is a progressive JavaScript framework suitable for building efficient and maintainable front-end applications. Its key features include: 1. Responsive data binding, 2. Component development, 3. Virtual DOM. Through these features, Vue.js simplifies the development process, improves application performance and maintainability, making it very popular in modern web development.

Is vue.js better than React?Is vue.js better than React?Apr 20, 2025 am 12:05 AM

Vue.js and React each have their own advantages and disadvantages, and the choice depends on project requirements and team conditions. 1) Vue.js is suitable for small projects and beginners because of its simplicity and easy to use; 2) React is suitable for large projects and complex UIs because of its rich ecosystem and component design.

Vue.js's Function: Enhancing User Experience on the FrontendVue.js's Function: Enhancing User Experience on the FrontendApr 19, 2025 am 12:13 AM

Vue.js improves user experience through multiple functions: 1. Responsive system realizes real-time data feedback; 2. Component development improves code reusability; 3. VueRouter provides smooth navigation; 4. Dynamic data binding and transition animation enhance interaction effect; 5. Error processing mechanism ensures user feedback; 6. Performance optimization and best practices improve application performance.

Vue.js: Defining Its Role in Web DevelopmentVue.js: Defining Its Role in Web DevelopmentApr 18, 2025 am 12:07 AM

Vue.js' role in web development is to act as a progressive JavaScript framework that simplifies the development process and improves efficiency. 1) It enables developers to focus on business logic through responsive data binding and component development. 2) The working principle of Vue.js relies on responsive systems and virtual DOM to optimize performance. 3) In actual projects, it is common practice to use Vuex to manage global state and optimize data responsiveness.

Understanding Vue.js: Primarily a Frontend FrameworkUnderstanding Vue.js: Primarily a Frontend FrameworkApr 17, 2025 am 12:20 AM

Vue.js is a progressive JavaScript framework released by You Yuxi in 2014 to build a user interface. Its core advantages include: 1. Responsive data binding, automatic update view of data changes; 2. Component development, the UI can be split into independent and reusable components.

Netflix's Frontend: Examples and Applications of React (or Vue)Netflix's Frontend: Examples and Applications of React (or Vue)Apr 16, 2025 am 12:08 AM

Netflix uses React as its front-end framework. 1) React's componentized development model and strong ecosystem are the main reasons why Netflix chose it. 2) Through componentization, Netflix splits complex interfaces into manageable chunks such as video players, recommendation lists and user comments. 3) React's virtual DOM and component life cycle optimizes rendering efficiency and user interaction management.

The Frontend Landscape: How Netflix Approached its ChoicesThe Frontend Landscape: How Netflix Approached its ChoicesApr 15, 2025 am 12:13 AM

Netflix's choice in front-end technology mainly focuses on three aspects: performance optimization, scalability and user experience. 1. Performance optimization: Netflix chose React as the main framework and developed tools such as SpeedCurve and Boomerang to monitor and optimize the user experience. 2. Scalability: They adopt a micro front-end architecture, splitting applications into independent modules, improving development efficiency and system scalability. 3. User experience: Netflix uses the Material-UI component library to continuously optimize the interface through A/B testing and user feedback to ensure consistency and aesthetics.

See all articles

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment