我正在使用 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();
}
}
然后我得到这个错误:
这个问题在这个问题中被修复 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/