小工具知识网

当前位置: 首页 > 行业知识 > JS+ Vue3前端框架|Vue3 超详细 -实现父子组件之间的通信

行业知识

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

2026-11-15 07:01:14 来源:互联网转载

Background:

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

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

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

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

示例:

父组件:   import { ref } from 'vue';import ChildComponent from './ChildComponent.vue'; const parentMessage = ref('Hello from Parent!'); 子组件(ChildComponent.vue):   {{ message }} import { defineProps } from 'vue'; const props = defineProps({  message: String});

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

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

示例:

子组件(ChildComponent.vue):  Send Message to Parent import { defineEmits } from 'vue'; const emit = defineEmits(['message-to-parent']); const sendMessageToParent = () => {  emit('message-to-parent', 'Hello from Child!');};父组件(ParentComponent.vue):    import { ref } from 'vue';import ChildComponent from './ChildComponent.vue'; const messageFromChild = ref(''); const receiveMessageFromChild = (message) => {  messageFromChild.value = message;};

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一个属性。

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

2: 子组件 A 和 B 注入共享状态

接下来,我们在子组件 A 和 B 中inject这个属性。

      

Component A: {{ sharedState.message }}

Change Message import { inject } from 'vue'; // 使用 inject 函数来注入 sharedStateconst sharedState = inject('sharedState'); const updateMessage = () => { sharedState.message = 'Updated message from Component A';}; Component B: {{ sharedState.message }} import { inject } from 'vue'; // 使用 inject 函数来注入 sharedStateconst sharedState = inject('sharedState');

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

3: 父组件作为中介

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

     import ChildComponentA from './ChildComponentA.vue';import ChildComponentB from './ChildComponentB.vue';

在这个例子中,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):

  Update Shared Message import { useStore } from 'vuex'; const store = useStore(); const updateSharedMessage = () => {  store.dispatch('setSharedMessage', 'Message updated by Component A');};

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

  Shared message: {{ sharedMessage }} import { computed } from 'vue';import { useStore } from 'vuex'; const store = useStore();const sharedMessage = computed(() => store.state.sharedMessage);

在 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

上一篇:多台服务器怎么部署devops?

下一篇:无需迅雷,替代下载方法全攻略