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

Nuxt/Vue中vue-bootstrap-typeahead输入框绑定@blur事件及添加属性方法

解决方案

1. 给内部input绑定@blur事件

通过ref获取组件实例后定位到内部input元素,手动绑定事件即可,无需修改组件源码,兼容性最好:
首先修改模板代码,给组件新增ref属性:

<vue-bootstrap-typeahead
   ref="plateTypeahead"
   v-model="plateNumberFilter"
   :data="plateNumberOptions"
   size="sm"
   required
   @hit="returnPlateNumberId()"
/>

在组件生命周期钩子中完成事件绑定:

export default {
  // 其他组件配置省略
  mounted() {
    // 定位到组件内部的input元素
    const inputEl = this.$refs.plateTypeahead.$el.querySelector('input.form-control')
    // 绑定blur事件
    inputEl.addEventListener('blur', this.myFunctionIsnnotTriggered)
  },
  // 组件销毁前移除事件监听,避免内存泄漏
  beforeUnmount() {
    const inputEl = this.$refs.plateTypeahead?.$el?.querySelector('input.form-control')
    if (inputEl) {
      inputEl.removeEventListener('blur', this.myFunctionIsnnotTriggered)
    }
  },
  methods: {
    myFunctionIsnnotTriggered() {
      // 此处写你要执行的业务逻辑
    },
    returnPlateNumberId() {
      // 原有逻辑保留
    }
  }
}

如果使用Nuxt3/Vue3 composition API,仅需替换ref获取元素的写法,绑定逻辑完全一致。

2. 给内部input添加id属性

在mounted钩子中拿到input元素后直接设置属性即可:

mounted() {
  const inputEl = this.$refs.plateTypeahead.$el.querySelector('input.form-control')
  // 给input设置自定义id
  inputEl.id = 'myElement'
}

3. 绑定自定义事件监听器

和绑定原生blur事件逻辑完全一致,替换为你需要的自定义事件名即可:

mounted() {
  const inputEl = this.$refs.plateTypeahead.$el.querySelector('input.form-control')
  // 绑定自定义事件,示例为my-custom-event,可替换为实际自定义事件名
  inputEl.addEventListener('my-custom-event', this.handleCustomEvent)
},
beforeUnmount() {
  const inputEl = this.$refs.plateTypeahead?.$el?.querySelector('input.form-control')
  if (inputEl) {
    inputEl.removeEventListener('my-custom-event', this.handleCustomEvent)
  }
},
methods: {
  handleCustomEvent(e) {
    // 自定义事件处理逻辑,可通过e.detail获取事件传递参数
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 03:45:04