I’m trying to trigger a function when I leave an input, but how I configured the input is by using vue-bootstrap-typehead
. By inspecting the input element in the DOM it would be structured like this:
JavaScript
x
4
1
<div id="myElement">
2
<div class="input-group input-group-sm">
3
<input type="search" autocomplete="off" class="form-control">
4
and this is my code:
JavaScript
1
10
10
1
<vue-bootstrap-typeahead
2
id="myElement"
3
v-model="plateNumberFilter"
4
:data="plateNumberOptions"
5
size="sm"
6
required
7
@blur="myFunctionIsnnotTriggered"
8
@hit="returnPlateNumberId()"
9
/>
10
I’ve tried adding the id="myElement"
on the typeahead itself but it puts the id
in the div
instead, which kinda makes sense, but I would’ve wanted it to be in the input
tag instead.
So I have 3 questions:
- How do I add an @blur on the input of
vue-bootstrap-typeahead
component? - How do I add an
id
in the input of avue-bootstrap-typeahead
component? - How do I add an eventListener in the
input
tag inside thevue-bootstrap-typeahead
component?
You don’t need to answer 2 if you have an answer for 1 and so on. But it would be cool to have an answer to all 3 of them.
Advertisement
Answer
The vue-typeahead-component
available events only include hit
and input
events, so you can’t apply @blur
to the component itself.
To add an event listener on the inner <input>
of vue-bootstrap-typeahead
:
- Use a template ref on the
<vue-bootstrap-typeahead>
component. - From the ref, get its root DOM element via
vm.$el
. - Use
Element.querySelector()
to get the inner<input>
. - Use
EventTarget.addEventListener('blur', handler)
to listen to theblur
event on the<input>
.
JavaScript
1
15
15
1
<template>
2
<vue-bootstrap-typeahead ref="typeahead" 1️⃣ />
3
</template>
4
5
<script>
6
export default {
7
async mounted() {
8
await this.$nextTick()
9
this.$refs.typeahead.$el 2️⃣
10
.querySelector('input') 3️⃣
11
.addEventListener('blur', (e) => console.log('blur', e)) 4️⃣
12
},
13
}
14
</script>
15