假设有大约<Form>个组件.可以使用@cancel事件监听器调用它,如果是这样,我想显示触发此事件的取消按钮.如果没有@cancel事件,取消按钮应该不可见.

有没有办法判断组件是否连接了事件侦听器?

目前我有:

<template>
  <form>
    <button v-if="cancelEventPassed" @click="$emit('cancel')">Cancel</button>
  </form>
</template>

这样称呼:

<Form :cancelEventPassed="true" @cancel="handle_cancel" />

任何一个

<Form/>

有没有可能在不使用任何额外属性(如cancelEventPassed)的情况下实现这一点?

推荐答案

当有监听器连接到组件时,它们在组件的$listeners属性中可用.

您可以使用该属性来确定特定的侦听器是否可用.例如,这里有一个computed属性,用于判断是否存在cancel个侦听器.

computed:{
  hasCancelListener(){
    return this.$listeners && this.$listeners.cancel
  }
}

下面是一个在组件中使用的示例.

console.clear()

Vue.component("CustomForm", {
  template:`
    <div>
      <h1>Custom Form</h1>
      <button v-if="hasCancelListener" @click="$emit('cancel')">I have a listener!</button>
    </div>
  `,
  computed:{
    hasCancelListener(){
      return this.$listeners && this.$listeners.cancel
    }
  },
})

new Vue({
  el: "#app",
  methods:{
    onCancel(){
      alert('canceled')
    }
  }
})
<script src="https://unpkg.com/vue@2.4.2"></script>
<div id="app">
  <custom-form @cancel="onCancel"></custom-form>
  <hr>
  <custom-form></custom-form>
</div>

Vue.js相关问答推荐

try 在类星应用程序中使用Vue插件(Vue 3 Mq)-如何配置?

可组合数据获取示例

如何以惯用的方式触发 vue3 中同级组件的效果?

Vuetify 3 v-radio-group 将模型设置为 null

将 v-calendar 与以时间和日期格式出现的事件一起使用

v-on 的 .native 修饰符仅在组件上有效,但在 标签上使用

如何在 vue2.7 中删除 slot-scope

如何使用 async/await 在 vue js 中添加标头

在 vue.js 中添加新类时样式不适用

Vue,Composition API:如何从react 式转换中跳过深度嵌套的属性?

在 Ajax 函数中访问 Vue.js 组件属性

VueJS CKeditor5 上传图片

使用带有 v-date-picker 的 new Date() 不起作用

如何更新手动安装的 vue 组件上的props?

使用 azure devops 发布管道部署 Vue.js 应用程序

Vuex - 如何跨不同选项卡持久存储更新?

SVG 加载 vue-svg-loader; [Vue 警告]:无效的组件定义

如何设置 :id 前缀字符串?

Vue 2 转换不起作用

Vue.JS 2.0 修改不相关数据时速度慢