If you’ve ever tested your work on iOS devices, you know that dismissing the keyboard is not as easy as tapping outside text inputs.
This issue can be simply fixed by calling blur()
on the input to blur it programmatically when the user taps outside it.
Knowing this, we’re left with two things to learn. First, we need to know how to detect clicks outside the input. Second, we need to make it the default behavior for all the inputs we have — so we need to make it reusable across the application.
The first one can be done simply with vue-closable, a vue plugin I created. In case you’re curious, I’ve written a tutorial on how I created this directive.
The second one can be achieved by creating a custom component for our input element. And in this component, we blur the input when clicking outside it. So with this approach, we’ll be sure that we’ll have this behavior in all of our input elements.
Now, let’s try this solution in a quick example.
Example
Let’s build this example quickly with Vue CLI 3’s Instant Prototyping.
So, in a new directory, create two files: App.vue
and BaseInput.vue
.
Next, put the following code into App.vue
:
<template>
<div class="app">
<base-input />
</div>
</template>
<script>
import Vue from 'vue'
import VueClosable from 'vue-closable'
Vue.use(VueClosable)
import BaseInput from './BaseInput'
export default {
components: { BaseInput }
}
</script>
We’re here displaying BaseInput
component (which we haven’t created yet). We’re also importing the vue-closable
plugin. This means, we have to install it:
npm install vue-closable --save
Let’s now implement BaseInput.vue
:
<template>
<input
class="base-input"
ref="input"
type="text"
v-closable="{
handler: 'onClick'
}"
/>
</template>
<script>
export default {
methods: {
onClick() {
this.$refs.input.blur()
}
}
}
</script>
So it’s a simple text input that gets blurred when the user clicks outside it. You can learn more about vue-closable from the docs, but all we’re doing here is specifying the handler that gets called when the user clicks outside the <input>
element.
If you check this example on your iOS device, you should be able to dismiss the keyboard by tapping outside it!