Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vuejs Typescript class component refs.focus not working

I am using Typescript Class component and I have this problem I can't use this.$refs.<refname>.focus()

Template Code:

 <header class="py-2 px-1 m-0 row">
    <input
      type="text"
      class="form-control m-1"
      ref="searchBoard"
      placeholder="Find boards by name..."
    />
  </header>

This input field is inside a popup.

Typescript Code:

import { Component, Vue } from "vue-property-decorator";

@Component
export default class BoardList extends Vue {

  // I added this to solve the compile error
  $refs!: {
    searchBoard: HTMLInputElement;
  };

  isShown = false;

  toggleDropdown() {
    this.isShown = !this.isShown;
    this.$refs.searchBoard.focus();
  }
} 

Then I get this Error:

enter image description here

this problem is fixed in this question Vuejs typescript this.$refs..value does not exist added:

  $refs!: {
    searchBoard: HTMLInputElement;
  };

I get a New Error in my console

[Vue warn]: Error in v-on handler: "TypeError: this.$refs.searchBoard is undefined"

found in

---> <BoardList> at src/components/boards/buttons/BoardList.vue
       <NavbarTop> at src/components/NavbarTop.vue
         <ComponentName> at src/App.vue
           <Root> vue.runtime.esm.js:619
    VueJS 

7

is there a way to do this?

like image 962
Evan Avatar asked Jun 19 '26 15:06

Evan


1 Answers

Regarding the use of setTimeout:

Based on the timing of your code, it seems your isShown property controls whether or not the $refs.searchBoard is rendered in the DOM. Instead of setTimeout, Vue recommends using $nextTick to defer an action until the next DOM cycle:

toggleDropdown() {
  this.isShown = !this.isShown
  this.$nextTick(() => this.$refs.searchBoard.focus())
}

Regarding $refs:

A slightly cleaner alternative to the $refs type extension in your class is to use @Ref:

@Component
export default class BoardList extends Vue {
  @Ref() readonly searchBoard!: HTMLInputElement

  toggleDropdown() {
    this.isShown = !this.isShown
    this.$nextTick(() => this.searchBoard.focus())
  }
}
like image 128
tony19 Avatar answered Jun 21 '26 14:06

tony19



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!