Vue3开发极简入门:组件间通信事件

www.jswusn.com Other 2025-06-12 09:42:32 4次浏览

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('事件名', 参数...)


技术分享

苏南名片

  • 联系人:吴经理
  • 电话:152-1887-1916
  • 邮箱:message@jswusn.com
  • 地址:江苏省苏州市相城区

热门文章

Copyright © 2018-2025 jswusn.com 版权所有

技术支持:苏州网站建设  苏ICP备18036849号