JS+ Vue3前端框架|Vue3 超详细 -实现父子组件之间的通信

Background:

随着单页面应用(SPA)的兴起,前端开发正逐渐转向基于组件的架构模式。在这种模式中,应用程序被拆分成多个独立且可重用的组件,这些组件需要能够有效地进行通信以协同工作。作为 Vue.js 框架的最新版本,Vue 3 通过提供多种组件间通信机制,使得状态管理和数据传递变得更加灵活高效。
在这里插入图片描述

组件间的数据传递通常源于应用状态管理的需求。不同的组件可能需要共享相同的状态或数据,或者一个组件的行为可能需要另一个组件做出相应的反应。在这些情况下,确保数据正确有效地流动对于保持应用逻辑的清晰性和稳定性至关重要。

一、父组件传值给子组件(Props)

在 Vue 3 中,父组件向子组件传递数据的方式与 Vue 2 类似,通过 props 实现。

示例:

父组件:

<template>
  <ChildComponent :message="parentMessage" />
</template>
 
<script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
 
const parentMessage = ref('Hello from Parent!');
</script>
 子组件(ChildComponent.vue): 

<template>
  <div>{{ message }}</div>
</template>
 
<script setup>
import { defineProps } from 'vue';
 
const props = defineProps({
  message: String
});
</script>

二、子组件传值给父组件(自定义事件)

通过 emit 函数实现了子组件向父组件传值的功能。

示例:

子组件(ChildComponent.vue):

<template>
  <button @click="sendMessageToParent">Send Message to Parent</button>
</template>
 
<script setup>
import { defineEmits } from 'vue';
 
const emit = defineEmits(['message-to-parent']);
 
const sendMessageToParent = () => {
  emit('message-to-parent', 'Hello from Child!');
};
</script>
父组件(ParentComponent.vue): 

<template>
  <ChildComponent @message-to-parent="receiveMessageFromChild" />
</template>
 
<script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
 
const messageFromChild = ref('');
 
const receiveMessageFromChild = (message) => {
  messageFromChild.value = message;
};
</script>

defineEmits 用于定义组件可以触发的事件。父组件通过 @message-to-parent 监听子组件发出的事件,并在事件发生时执行 receiveMessageFromChild 方法。

三、兄弟组件之间传值(提供/注入)

在Vue 3中,provide和inject API确实为非父子关系组件(如兄弟组件)提供了一种通信方式。这种方法通过定义一个可以被后代组件注入的依赖来工作,即使这些组件并非直接的父子关系也可以。要使用provide和inject实现兄弟组件间的通信,我们通常需要一个共同的祖先组件作为数据的“源头”。

以下面的组件结构为例:

- 祖先组件(AncestorComponent)
  - 父组件(ParentComponent)
    - 子组件 A(ChildComponentA)
    - 子组件 B(ChildComponentB)

这里,我们将在祖先组件中provide一个可以被子组件 A 和 B inject的属性。如果没有共同的直接祖先组件,你可以创建一个空的 Vue 实例或者使用一个全局状态管理库如Vuex.

1: 设置祖先组件
首先,我们在祖先组件中provide一个属性。

<!-- AncestorComponent.vue -->
<template>
  <ParentComponent />
</template>
 
<script setup>
import { reactive, provide } from 'vue';
import ParentComponent from './ParentComponent.vue';
 
// 创建一个响应式对象
const sharedState = reactive({
  message: 'Hello from Ancestor!'
});
 
// 使用 provide 函数来提供这个响应式对象
provide('sharedState', sharedState);
</script>

2: 子组件 A 和 B 注入共享状态
接下来,我们在子组件 A 和 B 中inject这个属性。

<!-- ChildComponentA.vue -->
<template>
  <div>
    <p>Component A: {{ sharedState.message }}</p>
    <button @click="updateMessage">Change Message</button>
  </div>
</template>
 
<script setup>
import { inject } from 'vue';
 
// 使用 inject 函数来注入 sharedState
const sharedState = inject('sharedState');
 
const updateMessage = () => {
  sharedState.message = 'Updated message from Component A';
};
</script>
<!-- ChildComponentB.vue -->
<template>
  <div>Component B: {{ sharedState.message }}</div>
</template>
 
<script setup>
import { inject } from 'vue';
 
// 使用 inject 函数来注入 sharedState
const sharedState = inject('sharedState');
</script>

现在,无论是子组件 A 还是 B 任何一个更新了 sharedState.message 的值,另一个组件都会立即反映这个变化,因为它们共享了同一个响应式状态。

3: 父组件作为中介
在某些情况下,我们可能需要一个父组件来作为包含子组件 A 和 B 的容器。

<!-- ParentComponent.vue -->
<template>
  <ChildComponentA />
  <ChildComponentB />
</template>
 
<script setup>
import ChildComponentA from './ChildComponentA.vue';
import ChildComponentB from './ChildComponentB.vue';
</script>

在这个例子中,ParentComponent 仅作为布局容器,而实际的状态共享逻辑在AncestorComponent 和子组件 A、B 之间通过 provide 和 inject 实现的。这种方法的优点在于,它避免了使用全局状态管理库,同时仍然能够以一种组织良好且易于维护的方式来共享状态。

四、兄弟组件之间传值(Vuex)

对于更复杂的状态管理,Vue 3 继续支持 Vuex,一个专为 Vue 应用程序开发的状态管理库。

示例:安装 Vuex 4(适用于 Vue 3):

npm install vuex@next --save
创建 Vuex store(store.js):

import { createStore } from 'vuex';
 
export default createStore({
  state() {
    return {
      sharedMessage: 'Initial shared message'
    };
  },
  mutations: {
    updateSharedMessage(state, newMessage) {
      state.sharedMessage = newMessage;
    }
  },
  actions: {
    setSharedMessage({ commit }, newMessage) {
      commit('updateSharedMessage', newMessage);
    }
  }
});

在主文件中 (main.js) 引入并使用 store:

import { createApp } from 'vue';
import App from './App.vue';
import store from './store';
 
createApp(App).use(store).mount('#app');

组件 A 更新 Vuex 状态(ComponentA.vue):

<template>
  <button @click="updateSharedMessage">Update Shared Message</button>
</template>
 
<script setup>
import { useStore } from 'vuex';
 
const store = useStore();
 
const updateSharedMessage = () => {
  store.dispatch('setSharedMessage', 'Message updated by Component A');
};
</script>

组件 B 访问 Vuex 状态(ComponentB.vue):

<template>
  <div>Shared message: {{ sharedMessage }}</div>
</template>
 
<script setup>
import { computed } from 'vue';
import { useStore } from 'vuex';
 
const store = useStore();
const sharedMessage = computed(() => store.state.sharedMessage);
</script>

在 Vuex 的示例中,ComponentA 通过调用 store.dispatch 方法来触发 action,从而更新 store 中的状态。而 ComponentB 则通过计算属性(computed property)来响应这个状态的变化。

Summary

Vue 3 引入了多种方法,以支持组件之间的通信,这些方法适用于不同复杂度的通信需求。当涉及到父与子组件之间的交流时,使用属性(props)和自定义事件仍然是基本的选择。对于需要在同一层级间通信的兄弟组件,提供了 provide 和 inject 机制。另外,对于规模较大的应用程序,管理全局状态的任务通常交由 Vuex 来负责。了解并掌握这些不同的通信方式及其优缺点,将有助于你创建出更加容易维护且高效的 Vue 应用。
————————————————
参考链接:
https://blog.csdn.net/weixin_47192158/article/details/138181804
https://blog.csdn.net/qq_38423256/article/details/128632936

  • 25
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王东韦DvWooo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值