typescriptvue.jsvuejs2vue-class-components

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?


Solution

  • 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())
      }
    }