typescript - Vuejs Typescript 类组件 refs.focus 不工作

标签 typescript vue.js vuejs2 vue-class-components

我正在使用 Typescript 类组件,但遇到无法使用的问题 this.$refs.<refname>.focus()

模板代码:

 <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>

此输入字段位于弹出窗口内。

typescript 代码:

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

然后我得到这个错误:

enter image description here

这个问题在这个问题中被修复 Vuejs typescript this.$refs..value does not exist 添加:

  $refs!: {
    searchBoard: HTMLInputElement;
  };

我的控制台出现新错误

[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

有办法吗?

最佳答案

关于setTimeout的使用:

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

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

关于$refs:

$refs type extension 稍微干净一点的替代品在你的课上是使用@Ref :

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

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

关于typescript - Vuejs Typescript 类组件 refs.focus 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60174338/

相关文章:

Angular 13 Prerender 错误找不到主包

javascript - 在方法中表达异步方法

javascript - 访问 Vue 实例上不存在的属性失败

javascript - 过滤数组并匹配至少一个条件

javascript - 将 Grunt 与 VueJS 结合使用

typescript - 在 TypeScript 中以字符串形式获取枚举名称

typescript - 为什么 typescript 会在不相关的类之间隐式转换?

javascript - 如何在方法之外使用google-translate-api翻译?

javascript - Vue.js : form-data Event

typescript - HERE map javascript API : How to apply styling from the style editor (. json)