Search code examples
javascriptvue.jsnativescriptnativescript-vue

NativeScript Vue - set focus on TextField


I am using NativeScript ("nativescript-vue": "^2.5.0") testing on iOS 13

"tns-android": {
      "version": "6.0.0"
    },
    "tns-ios": {
      "version": "6.0.1"
    }

Trying to set focus to on TextField when taping a button, it currently looks like this

  <GridLayout dock="top" columns="auto,*,auto" width="70%" rows="auto,auto">
    <Label text.decode="&#xf2bd;" horizontalAlignment="left" row="0" rowSpan="2"  col="0" />
    <Label text="USER" horizontalAlignment="left" row="0" col="1" class="m-l-3" />
    <Label :text="userEditBtnText"  @tap="userEditTap()"  horizontalAlignment="right" row="0" rowSpan="2" col="2" class="btnEdit"/>
    <TextField ref="userid" text="@username" :editable="userEdit" horizontalAlignment="left" row="1" col="1" class="m-l-3"/>
  </GridLayout>           

and the code for @tap="userEditTap()"

userEditTap(){
  this.userEdit = true;
  this.userEditBtnText="SAVE";
  this.$refs["userid"].focus();      
}

and my console error:

JavaScript error: file: node_modules/@nativescript/core/application/application.ios.js:312:26 JS ERROR Error: NativeScript encountered a fatal error: TypeError: this.$refs["userid"].focus is not a function. (In 'this.$refs["userid"].focus()', 'this.$refs["userid"].focus' is undefined)

any input is appreciated!


Solution

  • When you access by ref you are accessing the Vue element, you will have to call .nativeView to access the actual TextField.

    It should be,

    this.$refs["userid"].nativeView.focus();