vue.js - 在 Vue 3 + TypeScript + Options API 中使用 refs
问题描述
我试图了解将 refs 与 TypeScript 和 Options API 一起使用的最佳方式。在文档中,他们像下面这样引用它,但那是没有使用 TS。对于 TS,他们只解释了如何将其与 Composition API 一起使用。
当我使用this.$refs.myRef
它时会引发此错误Object is of type 'unknown'.
我知道我可以投射它并像这样使用它:(this.$refs.myRef as HTMLElement)
但我觉得没有必要每次都为每个 ref 做。
使用 Options API + TS 引用的正确方法是什么?
解决方案
我创建了一个这样的垫片:
垫片-运行时-core.d.ts
import * as runtimeCore from '@vue/runtime-core'
declare module '@vue/runtime-core' {
interface ComponentCustomProperties {
$refs: {
[key: string]: HTMLElement|any,
},
// ... more stuff
}
}
然后我可以像往常一样访问参考文献。
推荐阅读
- asp.net-core-mvc - SignInManager.IsSignedIn(User) 在身份脚手架上返回 false
- javascript - 如何在 Javascript 中将 Django 对象作为参数发送?
- javascript - 如何在 VScode 终端中显示 1:node?
- python - 对于 int() 基数为 10 的 ValueError 无效文字,对于使用 tweepy 用 python 编码的 Twitter Bot
- java - 如何在遍历循环时在 StringBuilder String 之间添加新行?
- java - 如何获取单元格字体颜色
- reactjs - 如何将数据从组件传递到 ReactJS 中的表单提交?
- arrays - get index of all True elements in array column in pyspark
- android - 如何正确设置带有 URI 的 ImageView?
- assembly - 编译器是否只完全展开外循环?