Vuejs Typescript class component refs.focus not working

Van*_*anz 1 typescript vue.js vuejs2 vue-class-components

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>
Run Code Online (Sandbox Code Playgroud)

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();
  }
} 
Run Code Online (Sandbox Code Playgroud)

Then I get this Error:

在此处输入图片说明

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

  $refs!: {
    searchBoard: HTMLInputElement;
  };
Run Code Online (Sandbox Code Playgroud)

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 
Run Code Online (Sandbox Code Playgroud)

7

is there a way to do this?

ton*_*y19 6

关于使用setTimeout

根据您的代码时间,您的isShown属性似乎控制着 是否$refs.searchBoard在 DOM 中呈现。代替setTimeout,Vue 建议使用$nextTick将操作推迟到下一个 DOM 周期:

toggleDropdown() {
  this.isShown = !this.isShown
  this.$nextTick(() => this.$refs.searchBoard.focus())
}
Run Code Online (Sandbox Code Playgroud)

关于$refs

班级中$refs类型扩展的一个更简洁的替代方法是使用@Ref

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

  toggleDropdown() {
    this.isShown = !this.isShown
    this.$nextTick(() => this.searchBoard.focus())
  }
}
Run Code Online (Sandbox Code Playgroud)