Vue3兄弟组件传值

Vue3.0中兄弟组件传值有很多种方法,今天我们介绍两种,一种是A——父——B,还有一种是使用插件mitt

mitt插件

使用npm 或者cnpm 下载插件 mitt
npm install mitt -S

新建文件夹 utils新建文件Bus.ts

import mitt from 'mitt';

const emitter = mitt();
export default emitter;

在父组件中引入A,B组件

<template>
  <div>
    <A @fn="getmsg" />
    <B :Amsg="Amsg" />
  </div>
</template>

<script setup>
  import A from './A.vue';
  import B from './B.vue';
</script>

<style></style>

在A组件中引入emitter.emit,传给将值传给Fn

<template>
  <div>
    <h1>我是A组件</h1>
    <button @click="Busbtn">bus按钮</button>
  </div>
</template>

<script setup>
  import { ref } from 'vue';
  import emitter from '../../utils/Bus.ts';
  const Btnmsg = ref('我是A组件Btnmsg的值');
  // mmit
  const Busbtn = () => {
    emitter.emit('Fn', Btnmsg);
  };
</script>

<style></style>

在B组件中使用emitter.on接收数据

<template>
  <div>
    <h1>我是B组件</h1>
    {{ ABtnmsg }}
  </div>
</template>

<script setup>
  import { ref, onMounted } from 'vue';
  import emitter from '../../utils/Bus.ts';
  // mitt
  let ABtnmsg = ref('');
  onMounted(() => {
    emitter.on('Fn', (e) => {
      ABtnmsg.value = e.value;
    });
  });
  // 移除指定事件
    emitter.off('Fn');
    // 移除全部事件
    emitter.all.clear();
</script>

<style></style>

使用A——父——B

父组件

<!--
 * @Author: wangyf 1758985226@qq.com
 * @Date: 2023-07-04 09:26:23
 * @LastEditors: wangyf 1758985226@qq.com
 * @LastEditTime: 2023-07-04 09:44:53
 * @FilePath: \fast-vue3\src\pages\brother\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div>
    <A @fn="getmsg" />
    <B :Amsg="Amsg" />
  </div>
</template>

<script setup>
  import A from './A.vue';
  import B from './B.vue';
  import { ref } from 'vue';
  const Amsg = ref('');
  const getmsg = (n) => {
    Amsg.value = n.value;
  };
</script>

<style></style>

A组件

<template>
  <div>
    <h1>我是A组件</h1>
    <button @click="btn">按钮</button><br />
  </div>
</template>

<script setup>
  import { ref } from 'vue';
  const Emit = defineEmits('Fn');
  const msg = ref('我是A组件的值');
  const btn = () => {
    Emit('Fn', msg);
  };
</script>

<style></style>

B组件

<template>
  <div>
    <h1>我是B组件</h1>
    {{ Amsg }}
    <hr />
    {{ ABtnmsg }}
  </div>
</template>

<script setup>
  import { ref, onMounted } from 'vue';
  const props = defineProps({
    Amsg: {
      type: String,
      default: 'ooo',
    },
  });
</script>

<style></style>

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值