当前位置:首页 > 科技  > 软件

Vue3.js组件通信,兄弟组件、父子、祖孙组件间通信

来源: 责编: 时间:2024-01-09 08:51:51 337观看
导读在 Vue.js 3 中,组件通信主要包括父子组件通信、兄弟组件通信以及祖孙组件通信。以下是各种情况下的常见通信方式:1. 父子组件通信:1.1 Props 传递数据:父组件通过 props 向子组件传递数据:<!-- Parent.vue --><template>

在 Vue.js 3 中,组件通信主要包括父子组件通信、兄弟组件通信以及祖孙组件通信。以下是各种情况下的常见通信方式:J4E28资讯网——每日最新资讯28at.com

1. 父子组件通信:

1.1 Props 传递数据:

父组件通过 props 向子组件传递数据:J4E28资讯网——每日最新资讯28at.com

<!-- Parent.vue --><template>  <Child :message="parentMessage" /></template><script>import Child from './Child.vue';export default {  data() {    return {      parentMessage: 'Hello from Parent!'    };  },  components: {    Child  }};</script><!-- Child.vue --><template>  <div>{{ message }}</div></template><script>export default {  props: ['message']};</script>

1.2 事件监听子组件:

子组件通过 $emit 触发事件,父组件通过监听这些事件来响应:J4E28资讯网——每日最新资讯28at.com

<!-- Parent.vue --><template>  <Child @notifyParent="handleNotify" /></template><script>import Child from './Child.vue';export default {  methods: {    handleNotify(message) {      console.log(message); // 处理从子组件传递的数据    }  },  components: {    Child  }};</script><!-- Child.vue --><template>  <button @click="notifyParent">Notify Parent</button></template><script>export default {  methods: {    notifyParent() {      this.$emit('notifyParent', 'Hello from Child!');    }  }};</script>

1.3 definEexpose暴露子组件方法

在 Vue 3 中,使用 TypeScript 编写组件时,如果想要将子组件的方法暴露给父组件,可以使用 defineExpose 函数。defineExpose 允许你定义哪些内容应该被暴露给父组件,以供父组件访问。J4E28资讯网——每日最新资讯28at.com

下面是一个简单的例子,演示如何在子组件中使用 defineExpose 暴露方法:J4E28资讯网——每日最新资讯28at.com

// ChildComponent.vue<template>  <div>    <button @click="incrementCounter">Increment Counter</button>  </div></template><script setup>import { ref, defineExpose } from 'vue';const counter = ref(0);const incrementCounter = () => {  counter.value++;};// 暴露方法给父组件defineExpose({  incrementCounter});</script>

在这个例子中,incrementCounter 方法被定义在子组件中,并通过 defineExpose 函数进行了暴露。父组件可以通过子组件的引用来调用这个方法。J4E28资讯网——每日最新资讯28at.com

// ParentComponent.vue<template>  <div>    <ChildComponent ref="childRef" />    <button @click="callChildMethod">Call Child Method</button>  </div></template><script setup>import { ref } from 'vue';const childRef = ref();const callChildMethod = () => {  // 调用子组件的方法  childRef.value.incrementCounter();};</script>

在父组件中,通过 ref 引用子组件,然后可以调用子组件中暴露的方法。J4E28资讯网——每日最新资讯28at.com

这样,通过 defineExpose 可以在 Vue 3 中很方便地实现子组件方法的暴露。这对于构建可重用组件库或复杂组件通信场景非常有用。J4E28资讯网——每日最新资讯28at.com

$listeners批量绑定子组件事件

$listeners 是一个对象,包含了父组件传递给子组件的所有事件监听器。这个对象允许子组件将所有未被自身处理的事件监听器绑定到合适的 HTML 元素上。J4E28资讯网——每日最新资讯28at.com

通常情况下,当你在子组件中使用 v-on="$listeners" 时,它会将所有的父组件传递下来的事件监听器应用到相应的 DOM 元素上。J4E28资讯网——每日最新资讯28at.com

以下是一个简单的例子,演示了 $listeners 的使用:J4E28资讯网——每日最新资讯28at.com

<!-- ParentComponent.vue --><template>  <ChildComponent @custom-event="handleCustomEvent" /></template><script>import ChildComponent from './ChildComponent.vue';export default {  methods: {    handleCustomEvent(data) {      console.log('Custom Event Handled in Parent:', data);    }  },  components: {    ChildComponent  }};</script>
<!-- ChildComponent.vue --><template>  <div>    <button @click="triggerCustomEvent">Trigger Custom Event</button>  </div></template><script>export default {  methods: {    triggerCustomEvent() {      // 触发自定义事件并传递数据      this.$emit('custom-event', 'Hello from Child');    }  }};</script>

在子组件中,当用户点击按钮时,触发了一个自定义事件,并通过 $emit 传递了数据给父组件。如果你希望在父组件中使用该事件监听器,可以通过 $listeners 将其传递到子组件的相应元素上:J4E28资讯网——每日最新资讯28at.com

<!-- ChildComponent.vue --><template>  <div>    <button @click="triggerCustomEvent" v-on="$listeners">Trigger Custom Event</button>  </div></template><script>export default {  methods: {    triggerCustomEvent() {      // 触发自定义事件并传递数据      this.$emit('custom-event', 'Hello from Child');    }  }};</script>

现在,在父组件中,你可以监听子组件触发的 custom-event 事件:J4E28资讯网——每日最新资讯28at.com

<!-- ParentComponent.vue --><template>  <ChildComponent @custom-event="handleCustomEvent" /></template><script>import ChildComponent from './ChildComponent.vue';export default {  methods: {    handleCustomEvent(data) {      console.log('Custom Event Handled in Parent:', data);    }  },  components: {    ChildComponent  }};</script>

在这个例子中,v-on="$listeners" 将所有父组件传递的事件监听器应用到了按钮上,这样子组件就能够触发相应的事件并将数据传递给父组件。J4E28资讯网——每日最新资讯28at.com

2. 兄弟组件通信:

2.1 通过共享状态(使用父组件):

通过将状态提升到共同的父组件,然后通过 props 和事件来实现兄弟组件之间的通信。J4E28资讯网——每日最新资讯28at.com

2.2 使用事件总线(Bus):

创建一个事件总线,兄弟组件通过事件总线来通信。在 Vue 3 中,可以使用 provide/inject 来创建一个简单的事件总线。J4E28资讯网——每日最新资讯28at.com

// EventBus.jsimport { createApp, ref } from 'vue';const bus = createApp();bus.provide('eventBus', bus);// ComponentA.vue<script>export default {  methods: {    notifySibling() {      this.$root.eventBus.emit('siblingEvent', 'Hello from Component A!');    }  }};</script>// ComponentB.vue<script>export default {  created() {    this.$root.eventBus.on('siblingEvent', message => {      console.log(message); // 处理从兄弟组件传递的数据    });  }};</script>

3. 祖孙组件通信:

3.1 通过 provide/inject:

使用 provide/inject 可以实现祖孙组件之间的通信,祖先组件通过 provide 提供数据,孙子组件通过 inject 获取数据。J4E28资讯网——每日最新资讯28at.com

<!-- Grandparent.vue --><template>  <Parent /></template><script>import { ref } from 'vue';import Parent from './Parent.vue';export default {  setup() {    const grandparentMessage = ref('Hello from Grandparent!');    provide('grandparentMessage', grandparentMessage);    return {      grandparentMessage    };  },  components: {    Parent  }};</script><!-- Parent.vue --><template>  <Child /></template><script>import Child from './Child.vue';export default {  components: {    Child  }};</script><!-- Child.vue --><template>  <div>{{ grandparentMessage }}</div></template><script>import { inject } from 'vue';export default {  setup() {    const grandparentMessage = inject('grandparentMessage');    return {      grandparentMessage    };  }};</script>

4. Vuex(全局状态管理):

如果你的应用中需要管理全局状态,Vuex 是一个强大的状态管理库。通过将状态存储在 Vuex 中,不同组件可以通过 Vuex 的 store 来实现通信。J4E28资讯网——每日最新资讯28at.com

// store.jsimport { createStore } from 'vuex';export default createStore({  state: {    message: 'Hello from Vuex!'  },  mutations: {    updateMessage(state, newMessage) {      state.message = newMessage;    }  },  actions: {    changeMessage({ commit }, newMessage) {      commit('updateMessage', newMessage);    }  }});// ComponentA.vue<script>export default {  computed: {    message() {      return this.$store.state.message;    }  },  methods: {    changeMessage() {      this.$store.dispatch('changeMessage', 'New Message');    }  }};</script>// ComponentB.vue<script>export default {  computed: {    message() {      return this.$store.state.message;    }  }};</script>

在 Vue.js 生态系统中,除了 $listeners 之外,还有一些其他状态管理库,其中包括 Pinia 和 Tini。这两个库提供了不同的方式来处理状态管理,和 Vuex 一样,它们都是 Vue 3 的状态管理库。J4E28资讯网——每日最新资讯28at.com

5. Pinia:

Pinia 是一个由 Vue.js 团队开发的状态管理库,旨在提供简单、灵活且性能出色的状态管理方案。与 Vuex 不同,Pinia 使用了更现代的 API,并且是基于 Composition API 构建的。J4E28资讯网——每日最新资讯28at.com

Pinia 的特点:J4E28资讯网——每日最新资讯28at.com

  • 使用 Composition API 构建。
  • 具有 TypeScript 支持。
  • 基于 Vue 3 的响应式系统。
  • 使用插件系统轻松扩展功能。

安装 Pinia:J4E28资讯网——每日最新资讯28at.com

npm install pinia

使用 Pinia:J4E28资讯网——每日最新资讯28at.com

import { createPinia } from 'pinia';const pinia = createPinia();export const useStore = pinia.createStore({  state: () => ({ count: 0 }),  actions: {    increment() {      this.state.count++;    }  }});

6.mitt

mitt 是一个简单而小巧的事件总线库,用于在应用程序的不同部分之间进行事件通信。它提供了一种简单的方式来发射和监听事件。与 Vuex 的 $emit 和 $on 类似,但 mitt 更为轻量。J4E28资讯网——每日最新资讯28at.com

下面是 mitt 的基本用法:J4E28资讯网——每日最新资讯28at.com

import mitt from 'mitt';// 创建事件总线const emitter = mitt();// 监听事件emitter.on('custom-event', (data) => {  console.log('Event Received:', data);});// 发射事件emitter.emit('custom-event', 'Hello from Mitt!');

在上面的代码中,emitter 是一个事件总线实例,可以用于在不同部分之间发送和接收事件。J4E28资讯网——每日最新资讯28at.com

本文链接:http://www.28at.com/showinfo-26-58936-0.htmlVue3.js组件通信,兄弟组件、父子、祖孙组件间通信

声明:本网页内容旨在传播知识,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。邮件:2376512515@qq.com

上一篇: 分享12个面向前端开发人员的设计工具,提高你的生产力

下一篇: 深入理解与应用多线程技术

标签:
  • 热门焦点
  • 微信语音大揭秘:为什么禁止转发?

    大家好,我是你们的小米。今天,我要和大家聊一个有趣的话题:为什么微信语音不可以转发?这是一个我们经常在日常使用中遇到的问题,也是一个让很多人好奇的问题。让我们一起来揭开这
  • 三万字盘点 Spring 九大核心基础功能

    大家好,我是三友~~今天来跟大家聊一聊Spring的9大核心基础功能。话不多说,先上目录:图片友情提示,本文过长,建议收藏,嘿嘿嘿!一、资源管理资源管理是Spring的一个核心的基础功能,不
  • 雅柏威士忌多款单品价格大跌,泥煤顶流也不香了?

    来源 | 烈酒商业观察编 | 肖海林今年以来,威士忌市场开始出现了降温迹象,越来越多不断暴涨的网红威士忌也开始悄然回归市场理性。近日,LVMH集团旗下苏格兰威士忌品牌雅柏(Ardbeg
  • 最“俊美”淘宝卖家,靠直播和短视频圈粉,上架秒光,年销3000万

    来源 | 电商在线文|易琬玉编辑|斯问受访店铺:Ringdoll戒之人形图源:微博@御座的黄山、&ldquo;Ringdoll戒之人形&rdquo;淘宝店铺有关外貌的评价,黄山已经听累了。生于1985年的他,哪
  • “又被陈思诚骗了”

    作者|张思齐 出品|众面(ID:ZhongMian_ZM)如今的国产悬疑电影,成了陈思诚的天下。最近大爆电影《消失的她》票房突破30亿断层夺魁暑期档,陈思诚再度风头无两。你可以说陈思诚的
  • 疑似小米14外观设计图曝光:后置相机模组变化不大

    下半年的大幕已经开启,而谁将成为下半年手机圈的主角就成为了大家关注的焦点,其中被传有望拿下新一代骁龙8 Gen3旗舰芯片的小米14系列更是备受大家瞩
  • SN570 NVMe SSD固态硬盘 价格与性能兼具

    SN570 NVMe SSD固态硬盘是西部数据发布的最新一代WD Blue系列的固态硬盘,不仅闪存技术更为精进,性能也得到了进一步的跃升。WD Blue SN570 NVMe SSD的包装外
  • 最薄的14英寸游戏笔记本电脑 Alienware X14已可以购买

    2022年1月份在国际消费电子展(CES2022)上首次亮相的Alienware新品——Alienware X14现在已经可以购买了,这款笔记本电脑被誉为世界上最薄的 14 英寸游戏笔
  • 北京:科技教育体验基地开始登记

      北京“科技馆之城”科技教育体验基地登记和认证工作日前启动。首批北京科技教育体验基地拟于2023年全国科普日期间挂牌,后续还将开展常态化登记。  北京科技教育体验基
Top