3.组件间通信-mitt(任意组件间通信)

mitt任意组件间通信
父组件:

<template>
  <div class="father">
    <h3>父组件</h3>
    <Child1/>
    <Child2/>
  </div>
</template>
<script setup lang="ts" name="Father">
  import Child1 from './Child1.vue'
  import Child2 from './Child2.vue'
</script>

<style scoped>
	.father{
		background-color:rgb(165, 164, 164);
		padding: 20px;
    border-radius: 10px;
	}
  .father button{
    margin-left: 5px;
  }
</style>

子组件1:

<template>
  <div class="child1">
    <h3>子组件1</h3>
		<h4>玩具:{{ toy }}</h4>
		<button @click="emitter.emit('send-toy',toy)">传递数据给子组件2</button>
  </div>
</template>
<script setup lang="ts" name="Child1">
	import {ref} from 'vue'
	import emitter from '@/utils/emitter';
	// 数据
	let toy = ref('奥特曼')
</script>
<style scoped>
	.child1{
		margin-top: 50px;
		background-color: skyblue;
		padding: 10px;
		box-shadow: 0 0 10px black;
		border-radius: 10px;
	}
	.child1 button{
		margin-right: 10px;
	}
</style>

子组件2:

<template>
  <div class="child2">
    <h3>子组件2</h3>
		<h4>电脑:{{ computer }}</h4>
		<h3 v-show="toy">组件1传递过来的数据:{{ toy }}</h3>
  </div>
</template>
<script setup lang="ts" name="Child2">
	import {ref,onUnmounted} from 'vue'
	import emitter from '@/utils/emitter';
	// 数据
	let computer = ref('联想')
	let toy = ref('')
	emitter.on('send-toy',(value:string)=>{
		console.log('得到子组件1传递过来的数据',value);
		toy.value = value
	})
</script>
<style scoped>
	.child2{
		margin-top: 50px;
		background-color: orange;
		padding: 10px;
		box-shadow: 0 0 10px black;
		border-radius: 10px;
	}
</style>

相关推荐

  1. 3.组件通信-mitt任意组件通信

    2024-06-09 14:34:03       12 阅读
  2. Vue3组件通信-$refs和$parent的使用

    2024-06-09 14:34:03       16 阅读
  3. 4.组件通信-v-model

    2024-06-09 14:34:03       8 阅读
  4. 07.组件通信-provide-inject(祖孙通信

    2024-06-09 14:34:03       14 阅读
  5. 小程序自定义组件——组件通信与事件

    2024-06-09 14:34:03       40 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-06-09 14:34:03       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-09 14:34:03       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-09 14:34:03       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-09 14:34:03       20 阅读

热门阅读

  1. spring boot集成pg

    2024-06-09 14:34:03       9 阅读
  2. !力扣70. 爬楼梯

    2024-06-09 14:34:03       9 阅读
  3. 微信小程序:实现音乐播放器的功能

    2024-06-09 14:34:03       6 阅读
  4. oracle10g的dataguard测试

    2024-06-09 14:34:03       12 阅读
  5. 电商系统中热库和冷库的使用与数据转换

    2024-06-09 14:34:03       8 阅读
  6. Python R用法:深度探索与实用技巧

    2024-06-09 14:34:03       9 阅读
  7. K-means聚类模型

    2024-06-09 14:34:03       10 阅读
  8. RAGFlow 学习笔记

    2024-06-09 14:34:03       10 阅读
  9. tcpdump 抓包

    2024-06-09 14:34:03       9 阅读
  10. TypeScript看这篇就够了

    2024-06-09 14:34:03       12 阅读
  11. 【分享】使用 Reducer 和 Context 拓展你的应用

    2024-06-09 14:34:03       13 阅读