emit就是事件Event。
这一节没废话,直接上代码,父组件:
<template> <div class="father"> <h1>父组件</h1> 装货地:北京,卸货地:海口,发车时间:{{ departTime }} <!-- 监听子组件的事件,并设置回调函数 --> <Son @set-depart-time="setDepartTime"/> </div> </template> <script lang='ts' setup name='Father'> import { ref } from 'vue'; import Son from './Son.vue'; const departTime = ref('待定') function setDepartTime(val: string) { departTime.value = val } </script> <style scoped> .father { background-color: darkseagreen; box-shadow: 0 0 10px black; border-radius: 10px; height: 100%; } </style>
子组件:
<template> <div class="son"> <h1>子组件</h1> 发车时间:{{ departTime }} <br> <button @click="letsGo">发车上报</button> </div> </template> <script lang='ts' setup name='Son'> import { ref } from 'vue'; const departTime = ref('待定') function letsGo() { departTime.value = "2024-01-01 11:11:11." + Math.random() // 触发事件&传参 emit('set-depart-time', departTime.value) } //声明事件,并返回emit以便进行相关操作 const emit = defineEmits(['set-depart-time']) </script> <style scoped> .son { background-color: silver; padding: 10px; margin-top: 10px; box-shadow: 0 0 10px black; border-radius: 10px; width: 90%; margin: auto; } </style>
说明:
父组件监听了子组件名为:set-depart-time的事件,其对应的回调函数是setDepartTime。
子组件通过
const emit = defineEmits(['事件名A','事件名B'])
声明了要触发的事件,并返回一个方法(emit)供我们使用。
子组件通过
emit('事件名', 参数...)