【发布时间】:2020-05-27 04:25:32
【问题描述】:
我正在使用 Typescript Class 组件,但我遇到了这个问题,我无法使用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>
此输入字段位于弹出窗口内。
打字稿代码:
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();
}
}
然后我得到这个错误:
这个问题在这个问题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
有没有办法做到这一点?
【问题讨论】:
-
HTMLFormElement 没有焦点方法。它应该改为 HTMLInputElement。
-
是的,我用 HTMLInputElement 更新了它,但我仍然在控制台中收到错误消息。 > “类型错误:this.$refs.searchBoard 未定义”
-
引用是非反应性的。您确定该元素不是有条件地呈现的(例如,在带有
v-if指令的元素中找到),并且在调用toggleDropdown方法时它绝对可用?如果您将this.$refs登录到控制台会发生什么? -
当我控制台它现在显示元素及其属性。但是焦点()不起作用
-
它现在可以工作了,我在 setTimeout() 中添加了 .focus()。很奇怪
标签: typescript vue.js vuejs2 vue-class-components