How to hide the keyboard for a SearchBar in NativeScript + Vue.js

Having trouble getting the keyboard to disappear for a search bar when working with NativeScript + Vue.js? Specifically with the SearchBar component, there isn’t an out of the box way of closing the keyboard without typing something and pressing the Search button.

Closing the Keyboard

Without searching you probably wouldn’t be able to figure this out, but the method that closes the keyboard is dismissSoftInput. To use it in combination with Vue.js you’ll need to first add a ref attribute to your component. Here’s an example:

<SearchBar hint="Search..." ref="searchBar" />

Then in your method you would access the component like this:

this.$refs.searchBar

Nothing new if you have worked with Vue.js before. Now, if you try to call dismissSoftInput from here you’ll get an error. That’s because accessing the component like this isn’t actually getting the “NativeScript” version of the component. It’s grabbing the Vue.js version.

There is a property that NativeScript adds to each component called nativeView. Using this nativeView property you can access the dismissSoftInput method. Here’s how you would call it in a method:

this.$refs.searchBar.nativeView.dismissSoftInput();

From here you should be able to use this to create a button that closes the keyboard. One thing you should know is that you can’t directly call this method in the mounted method. An error will occur if you do. You’ll need to call it within a setTimeout with a little bit of time for the timeout.

Hopefully you found this article helpful! When I was first trying to solve this problem it took a lot of searching to finally figure it out. These two pages specifically were how I eventually was able to get it:

https://discourse.nativescript.org/t/problem-with-hiding-keyboard-from-search-bar-on-page-load/5612/10
https://play.nativescript.org/?template=play-vue&id=60WzXJ&_ga=2.249796038.1797168816.1548048476-1181157931.1547867363

If you have any questions feel free to leave a comment below!