vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > Vue3组件通信

Vue3组件通信的方法大全

作者:訾博ZiBo

在Vue3中,组件通信仍然是一个非常重要的话题,因为在大多数应用程序中,不同的组件之间需要进行数据传递和交互,本文给大家介绍了Vue3组件通信的方法大全,需要的朋友可以参考下

一、 父子通信:最亲密、最常见的“家庭内部对话”

这是最基础也是最重要的通信方式,就像父母和孩子之间的日常交流。

1. Props (父 -> 子)

<template>
  <ChildComponent name="訾博" :age="18" />
</template>

<script setup>
import ChildComponent from './ChildComponent.vue';
</script>
<template>
  <p>大家好,我叫{{ name }},今年{{ age }}岁。</p>
</template>

<script setup>
// 接收父组件传来的props
const props = defineProps({
  name: String,
  age: {
    type: Number,
    required: true,
    default: 10
  }
});
</script>

2. Emits (子 -> 父)

子组件 (ChildComponent.vue):使用defineEmits声明事件,然后通过emit函数触发。

<template>
  <button @click="tellDad">告诉爸爸我长大了</button>
</template>

<script setup>
// 声明要触发的事件
const emit = defineEmits(['grow-up']);

function tellDad() {
  // 触发事件,并可以传递参数
  emit('grow-up', '我已经会自己写代码了!');
}
</script>

父组件 (Parent.vue):在子组件标签上使用@v-on监听事件。

<template>
  <ChildComponent @grow-up="handleChildGrowUp" />
  <p>来自儿子的消息:{{ messageFromChild }}</p>
</template>

<script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';

const messageFromChild = ref('');

function handleChildGrowUp(message) {
  messageFromChild.value = message;
}
</script>

3. v-model (双向绑定语法糖)

子组件 (CustomInput.vue)

<template>
  <input :value="modelValue" @input="emit('update:modelValue', $event.target.value)" />
</template>

<script setup>
defineProps(['modelValue']);
const emit = defineEmits(['update:modelValue']);
</script>

父组件 (Parent.vue)

<template>
  <CustomInput v-model="searchText" />
  <p>你在搜索:{{ searchText }}</p>
</template>

<script setup>
import { ref } from 'vue';
import CustomInput from './CustomInput.vue';

const searchText = ref('');
</script>

4. ref / $refs (父 -> 子)

子组件 (ChildComponent.vue):使用defineExpose暴露方法或属性。

<template>
  <p>我是一个深藏不露的组件</p>
</template>

<script setup>
import { ref } from 'vue';

const doPushUp = () => {
  console.log('正在做俯卧撑...');
};

// 把doPushUp方法暴露给父组件
defineExpose({
  doPushUp
});
</script>

父组件 (Parent.vue)

<template>
  <ChildComponent ref="childRef" />
  <button @click="commandChild">命令儿子</button>
</template>

<script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';

const childRef = ref(null);

function commandChild() {
  // 通过.value访问到子组件实例,并调用其暴露的方法
  childRef.value.doPushUp();
}
</script>

二、 跨代通信:当“爷爷”想和“孙子”说话

如果组件嵌套很深,一层一层地props下去,会累死人,这叫“Props Drilling”(属性钻探地狱)。为了避免这种情况,我们有更优雅的方案。

5. Provide / Inject

祖先组件 (GrandParent.vue)

<template>
  <ParentComponent />
</template>

<script setup>
import { provide, ref } from 'vue';

const themeColor = ref('dark');
// 提供数据,'theme'是暗号
provide('theme', themeColor); 
</script>

后代组件 (GrandChild.vue)

<template>
  <div :style="{ color: theme }">我是孙子组件,我用的是祖传主题色。</div>
</template>

<script setup>
import { inject } from 'vue';

// 注入数据,'theme'是暗号
const theme = inject('theme');
</script>

三、 任意组件通信:当“隔壁老王”想找你聊天

对于两个没有任何亲缘关系的组件,如何进行交流?

6. Pinia (官方推荐的状态管理库)

定义Store (/stores/user.js)

import { defineStore } from 'pinia';

export const useUserStore = defineStore('user', {
  state: () => ({
    name: '訾博',
    isLoggedIn: false,
  }),
  actions: {
    login() {
      this.isLoggedIn = true;
    },
  },
});

在任意组件中使用

<template>
  <p v-if="userStore.isLoggedIn">欢迎回来, {{ userStore.name }}!</p>
  <button @click="userStore.login()">登录</button>
</template>

<script setup>
import { useUserStore } from '@/stores/user';

const userStore = useUserStore();
</script>

7. Mitt / Tiny-emitter (全局事件总线)

创建广播站 (/utils/emitter.js)

import mitt from 'mitt';
const emitter = mitt();
export default emitter;

组件A (发送方)

<script setup>
import emitter from '@/utils/emitter';

function sendMessage() {
  emitter.emit('some-event', '来自A组件的问候');
}
</script>

组件B (接收方)

<script setup>
import emitter from '@/utils/emitter';
import { onMounted, onUnmounted } from 'vue';

onMounted(() => {
  emitter.on('some-event', (message) => {
    console.log(message); // "来自A组件的问候"
  });
});

// 记住,一定要在组件卸载时取消监听,否则会内存泄漏!
onUnmounted(() => {
  emitter.off('some-event');
});
</script>

总结与老师的忠告

訾博同学,我们来画个重点,做个总结:

场景推荐方法核心思想推荐指数
父 -> 子Props单向数据流,清晰明了★★★★★
子 -> 父Emits事件触发,解耦★★★★★
父子双向绑定v-modelprops和emits的语法糖★★★★★
跨代通信Provide / Inject依赖注入,避免属性钻探★★★★☆
复杂应用/任意组件Pinia集中式状态管理,可预测★★★★★
简单应用/任意组件Mitt (事件总线)发布订阅,简单灵活★★★☆☆
父组件调用子组件方法ref / defineExpose直接引用,应急手段★★☆☆☆

为师的忠告

  1. 首选“家庭内部”方案:优先使用 PropsEmits。这是Vue设计的核心,能让你的数据流向最清晰、最容易维护。
  2. 避免“属性钻探”:当 Props 需要传递超过两层时,就应该立刻考虑使用 Provide / Inject
  3. 拥抱“中央银行”:当多个组件共享同一份状态(比如用户信息、主题设置),并且这个状态会被多个组件修改时,不要犹豫,直接上 Pinia。它能让你的应用状态变得井井有条,而不是一团乱麻。
  4. 慎用“大喇叭”和“遥控器”Mittref 都有其用武之地,但它们也更容易导致代码难以追踪和维护。把它们当作你的“秘密武器”,非必要不使用。

专用于背诵的内容

訾博,把下面这段口诀背下来,面试和实战中定能助你一臂之力!

Vue3通信口诀

父传子,用 Props,儿子不能随便改。
子传父,靠 Emits,爹听事件乐开怀。
双向绑,v-model,省事方便真不赖。
爷孙传,ProvideInject 注入接过来。
兄弟情,状态乱,Pinia 银行管起来。
事件总线 Mitt 在,偶尔用用别依赖。
父控子,用 refexpose 暴露才存在。
牢记最佳实践,代码整洁人人爱!

以上就是Vue3组件通信的方法大全的详细内容,更多关于Vue3组件通信的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文