本文主要是介绍【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>
这篇关于【vue3】子传父-事件总线-mitt(子组件派发事件,父组件接收事件和传递的参数)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!