You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3 Options API:如何在父组件监听子组件按钮点击事件

Vue3 Options API 父组件监听子组件按钮点击事件解决方案

你之前用v-model的方式不对,v-model是用于数据双向绑定的,不是用来监听点击事件的。要实现父组件监听子组件按钮点击,用自定义事件的方式最直接,步骤如下:

1. 修改子组件 NotifDimsToLSRIncomformability

在按钮的点击方法里,通过$emit触发一个自定义事件,比如命名为close-notification:

<template>
  <cds-button 
    class="clsBtnClosePosition"
    action="primary"
    status="primary"
    size="md"
    type="button"
    @click="onCloseNotification()"
  > X
  </cds-button>
</template>

<script>
export default {
  methods: {
    onCloseNotification() {
      // 触发自定义事件,通知父组件按钮被点击
      this.$emit('close-notification')
      // 需要传递额外数据的话,可写成:this.$emit('close-notification', 额外数据)
    }
  }
}
</script>

2. 修改父组件(hosting-component)

在子组件标签上监听这个自定义事件,绑定父组件的处理方法:

<template>
  <NotifDimsToLSRIncomformability
    :showNotifDimsToLSRIncomformability="showNotifDimsToLSRIncomformability"
    @close-notification="handleNotificationClose"
  ></NotifDimsToLSRIncomformability>
</template>

<script>
export default {
  data() {
    return {
      showNotifDimsToLSRIncomformability: ... // 你的原有数据
    }
  },
  methods: {
    handleNotificationClose() {
      // 这里写你要执行的副作用操作,比如关闭弹窗、发送请求等
      console.log('子组件按钮被点击,执行父组件副作用')
      // 若子组件传了数据,可接收:handleNotificationClose(extraData)
    }
  }
}
</script>

补充说明

  • 如果你的vModel原本是用来控制组件显示隐藏的,可以保留,但要和事件监听分开:子组件通过props接收vModel,点击按钮时既$emit更新vModel(符合v-model语法),又触发点击事件;或者直接在父组件的handleNotificationClose里修改vModel的值,根据业务需求调整即可。
  • 自定义事件的命名可根据业务语义调整,比如close、notification-closed都可以,只要父组件和子组件对应上就行。

内容的提问来源于stack exchange,提问作者Amr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 03:37:14