当前位置: 首页 > news >正文

【vue3】子传父-事件总线-mitt(子组件派发事件,父组件接收事件和传递的参数)

安装库:cnpm install mitt

封装 eventbus.ts:

src->utils->eventbus.ts

//eventbus.tsimport mitt from 'mitt'const emitter = mitt()export default emitter

使用

B2.vue:

//B2.vue
<template><div class="aa"><p>子组件B</p><input v-model="info.name"><br><input v-model="info.age"><br><el-button type="primary" @click="emitB">派发一个事件</el-button></div>
</template><script setup lang='ts'>
import { ref } from 'vue'
import emitter from '../utils/eventbus';type tinfo = {name: string,age: number
}
const info = ref<tinfo>({ name: 'yyx', age: 12 })const emitB = () => {emitter.emit('on-click', info.value)
}</script>
<style scoped lang='scss'>
div {width: 400px;min-height: 300px;text-align: center;border: 1px solid #ccc;position: relative;
}
</style>

parent.vue:


//parent.vue
<template><div><p>这是父级</p><span>==================================</span><B2></B2><C2 :info="_info"></C2></div>
</template><script setup lang='ts'>
import { ref } from 'vue'
import emitter from '../utils/eventbus';
import B2 from '../components/B2.vue';
import C2 from '../components/C2.vue';let _info = ref<unknown>(null)emitter.on('on-click',(val)=>{_info.value = val
})</script>
<style scoped lang='scss'></style>

C2.vue:


//C2.vue
<template><div>组件3333333<p>name:{{ props?.info?.name }}</p><p>age:{{ props?.info?.age }}</p></div>
</template><script setup lang='ts'>type tprops = {info?: any //有个问号?,是可选的参数,父组件在饮用的时候,可以不传
}
const props = withDefaults(defineProps<tprops>(), {info:{name:'张三',age:20}
})</script><style scoped lang='scss'>
div {width: 400px;min-height: 300px;text-align: center;border: 1px solid #ccc;
}
</style>
http://www.lryc.cn/news/212737.html

相关文章:

  • 【杂记】java 大集合进行拆分
  • select...for update 锁表了?
  • 使用ControlNet生成视频(Pose2Pose)
  • 基于Docker使用Minikube
  • Stable Diffusion系列(一):古早显卡上最新版 WebUI 安装及简单操作
  • ruoyi框架前端vue部署生产环境教程
  • leetcode第369周赛
  • 如何在维格云中自动新增一行或多行数据?
  • Three.js 开发引擎的特点
  • k8s声明式资源管理方式
  • unity性能优化__Statistic状态分析
  • Linux Spug自动化运维平台公网远程访问
  • 3DES算法
  • 手机电池寿命检测
  • Vue项目搭建及使用vue-cli创建项目、创建登录页面、与后台进行交互,以及安装和使用axios、qs和vue-axios
  • AVL树、红黑树的介绍和实现[C++]
  • meta分析的异质性检验指标如何计算?
  • 如何在mac 安装 cocos 的 android环境
  • 作为网工有必要了解一下什么是SRv6?
  • Jmeter(十八):硬件性能监控指标详解
  • 【ARM Trace32(劳特巴赫) 使用介绍 2 -- Trace32 cmm 脚本基本语法及常用命令】
  • 2023年第七期丨全国高校大数据与人工智能师资研修班
  • 一文获取鼎捷医疗器械行业数智化合规敏态方案
  • 2023最新版本 FreeRTOS教程 -1-标准库移植FreeRTOS
  • python笔记(函数参数、面向对象、装饰器、高级函数、捕获异常)
  • JAVA命令总结
  • 删除的PPT怎么找回来?4个必备恢复方法!
  • Binder机制总结笔记
  • SQL SERVER 表分区
  • 从零开始学习PX4源码0(固件下载及编译)