当前位置:   article > 正文

前端|Vue Vue3 超详细 实现组件通信: 父子、子父及兄弟组件间的数据流转_vue3 父子传值之后数据变成proxy(array)

vue3 父子传值之后数据变成proxy(array)

背景:

随着单页面应用(SPA)的流行,前端开发逐渐转向组件化的架构。在这种架构中,应用被划分为多个互相独立、可复用的组件,这些组件需要能够高效地相互通信以协同工作。Vue 3,作为最新版的 Vue.js 框架,通过提供多种组件通信机制,使得状态管理和数据流转变得更加灵活和高效。

组件间传值的需要往往源于应用的状态管理需求。不同组件可能需要共享同一状态或数据,或者一个组件的行为需要另一个组件做出响应。在这些场景中,确保正确有效的数据流转对于维持应用逻辑的清晰和稳定性至关重要。

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

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

示例:

父组件(ParentComponent.vue):

  1. <template>
  2. <ChildComponent :message="parentMessage" />
  3. </template>
  4. <script setup>
  5. import { ref } from 'vue';
  6. import ChildComponent from './ChildComponent.vue';
  7. const parentMessage = ref('Hello from Parent!');
  8. </script>

 子组件(ChildComponent.vue): 

  1. <template>
  2. <div>{{ message }}</div>
  3. </template>
  4. <script setup>
  5. import { defineProps } from 'vue';
  6. const props = defineProps({
  7. message: String
  8. });
  9. </script>

在 Vue 3 中,我们使用 <script setup> 语法糖,这让组件定义更加简洁。ref 用于定义响应式数据,defineProps 则用于定义组件的 props。

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

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

示例:

子组件(ChildComponent.vue):

  1. <template>
  2. <button @click="sendMessageToParent">Send Message to Parent</button>
  3. </template>
  4. <script setup>
  5. import { defineEmits } from 'vue';
  6. const emit = defineEmits(['message-to-parent']);
  7. const sendMessageToParent = () => {
  8. emit('message-to-parent', 'Hello from Child!');
  9. };
  10. </script>

父组件(ParentComponent.vue): 

  1. <template>
  2. <ChildComponent @message-to-parent="receiveMessageFromChild" />
  3. </template>
  4. <script setup>
  5. import { ref } from 'vue';
  6. import ChildComponent from './ChildComponent.vue';
  7. const messageFromChild = ref('');
  8. const receiveMessageFromChild = (message) => {
  9. messageFromChild.value = message;
  10. };
  11. </script>

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

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

在Vue 3中,provideinject API确实为非父子关系组件(比如兄弟组件)提供了一种通信的方式。这种方法通过定义一个可以被后代组件注入的依赖来工作,即使这些组件不是直接的父子关系也可以。

要使用provideinject实现兄弟组件间的通信,我们通常需要一个共同的祖先组件来作为数据的“源头”。以下面的组件结构为例:

  1. - 祖先组件(AncestorComponent
  2. - 父组件(ParentComponent
  3. - 子组件 A(ChildComponentA
  4. - 子组件 B(ChildComponentB

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

 1: 设置祖先组件 

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

  1. <!-- AncestorComponent.vue -->
  2. <template>
  3. <ParentComponent />
  4. </template>
  5. <script setup>
  6. import { reactive, provide } from 'vue';
  7. import ParentComponent from './ParentComponent.vue';
  8. // 创建一个响应式对象
  9. const sharedState = reactive({
  10. message: 'Hello from Ancestor!'
  11. });
  12. // 使用 provide 函数来提供这个响应式对象
  13. provide('sharedState', sharedState);
  14. </script>
2: 子组件 A 和 B 注入共享状态 

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

  1. <!-- ChildComponentA.vue -->
  2. <template>
  3. <div>
  4. <p>Component A: {{ sharedState.message }}</p>
  5. <button @click="updateMessage">Change Message</button>
  6. </div>
  7. </template>
  8. <script setup>
  9. import { inject } from 'vue';
  10. // 使用 inject 函数来注入 sharedState
  11. const sharedState = inject('sharedState');
  12. const updateMessage = () => {
  13. sharedState.message = 'Updated message from Component A';
  14. };
  15. </script>
  1. <!-- ChildComponentB.vue -->
  2. <template>
  3. <div>Component B: {{ sharedState.message }}</div>
  4. </template>
  5. <script setup>
  6. import { inject } from 'vue';
  7. // 使用 inject 函数来注入 sharedState
  8. const sharedState = inject('sharedState');
  9. </script>

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

3: 父组件作为中介

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

  1. <!-- ParentComponent.vue -->
  2. <template>
  3. <ChildComponentA />
  4. <ChildComponentB />
  5. </template>
  6. <script setup>
  7. import ChildComponentA from './ChildComponentA.vue';
  8. import ChildComponentB from './ChildComponentB.vue';
  9. </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):

  1. import { createStore } from 'vuex';
  2. export default createStore({
  3. state() {
  4. return {
  5. sharedMessage: 'Initial shared message'
  6. };
  7. },
  8. mutations: {
  9. updateSharedMessage(state, newMessage) {
  10. state.sharedMessage = newMessage;
  11. }
  12. },
  13. actions: {
  14. setSharedMessage({ commit }, newMessage) {
  15. commit('updateSharedMessage', newMessage);
  16. }
  17. }
  18. });

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

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

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

  1. <template>
  2. <button @click="updateSharedMessage">Update Shared Message</button>
  3. </template>
  4. <script setup>
  5. import { useStore } from 'vuex';
  6. const store = useStore();
  7. const updateSharedMessage = () => {
  8. store.dispatch('setSharedMessage', 'Message updated by Component A');
  9. };
  10. </script>

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

  1. <template>
  2. <div>Shared message: {{ sharedMessage }}</div>
  3. </template>
  4. <script setup>
  5. import { computed } from 'vue';
  6. import { useStore } from 'vuex';
  7. const store = useStore();
  8. const sharedMessage = computed(() => store.state.sharedMessage);
  9. </script>

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

总结

Vue 3 提供了多种组件间通信的方式,这些方式满足了从简单父子通信到复杂全局状态管理的各种需求。props 和自定义事件依旧是父子组件通信的首选方式,provide 和 inject 提供了一种新的兄弟组件通信方法,而 Vuex 依旧是管理大型应用状态的强大工具。理解这些通信机制的适用场景和限制,将帮助你构建更加可维护和高效的 Vue 应用。 

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号