vue3中如何实现组件通信?

在 Vue 3 中,有多种方法可以实现组件之间的通信。以下是一些常见的方法:

1、Props 和 Events:父组件通过 props 向子组件传递数据,子组件通过触发事件向父组件发送消息。这是 Vue 中最基本的组件通信方式

props接收的数据是只读的

<!-- 父组件 -->
<template>
  <ChildComponent :message="parentMessage" @childEvent="handleChildEvent" />
</template>

<script setup lang="ts">
import ChildComponent from './ChildComponent.vue';
import {ref} from 'vue'
let parentMessage = ref('Hello from parent'),
const handleChildEvent = (payload) => {
      console.log('Received event from child:', payload);
}
</script>
<!-- 子组件 -->
<template>
  <div>
    <p>{{ props.message }}</p>
    <p>{{ message }}</p>
    <button @click="emitEvent">Send Event to Parent</button>
  </div>
</template>

<script setup lang="ts">
import {defineEmits} from 'vue'

const emit = defineEmits();

// 使用defineProperty来接收数据,defineProperty不需引入直接使用即可defineProps({})或defineProps([]),
// props中的是代理对象,在模板中使用可以省略props,在js中不可省略
const props = defineProps({ message: String});
const emitEvent = () =>{
      $emit('childEvent', 'Hello from child');
}
</script>

2、Provide 和 Inject:这是一种在组件树中跨级传递数据的方法。祖先组件通过 provide 选项提供数据,后代组件通过 inject 选项接收数据。

// 祖先组件
export default {
  provide() {
    return {
      sharedData: 'Shared data from ancestor',
    };
  },
};
// 后代组件
export default {
  inject: ['sharedData'],
};

3、Vuex:Vuex 是一个专门为 Vue.js 应用程序开发的状态管理模式。它可以帮助你管理应用程序中的共享状态,实现组件之间的通信。

首先,你需要安装 Vuex 并在你的应用程序中配置它:

npm install vuex@next --save

然后,创建一个 Vuex store:

// store.js
import { createStore } from 'vuex';

export default createStore({
  state: {
    count: 0,
  },
  mutations: {
    increment(state) {
      state.count++;
    },
  },
});

在你的应用程序中使用 store:

// main.js
import { createApp } from 'vue';
import App from './App.vue';
import store from './store';

createApp(App).use(store).mount('#app');

现在,你可以在组件中使用 this.$store 访问 store,并通过提交 mutation 或 dispatching action 来更新状态。

<!-- 组件 -->
<template>
  <div>
    <p>{{ $store.state.count }}</p>
    <button @click="$store.commit('increment')">Increment</button>
  </div>
</template>

这些方法可以根据你的需求和应用程序的复杂性来选择。对于简单的组件通信,Props 和 Events 通常就足够了。对于更复杂的应用程序,你可能需要考虑使用 Provide/Inject 或 Vuex。

4、类似vue2中的eventBus插件mitt 实现全局通信

5、使用useAttrs获取父组件传递过来的属性,props优先级比attrs高,若属性被props接收了 那么attrs中就接收不到了

6、ref、$parent (慎用)

7、provide、inject可以实现隔辈组件传递数据

8、pinia

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值