首页 > 解决方案 > 在 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 引用的正确方法是什么?

标签: vue.js

解决方案


我创建了一个这样的垫片:

垫片-运行时-core.d.ts

import * as runtimeCore from '@vue/runtime-core'

declare module '@vue/runtime-core' {
  interface ComponentCustomProperties {
    $refs: {
      [key: string]: HTMLElement|any,
    },
    // ... more stuff
  }
}

然后我可以像往常一样访问参考文献。


推荐阅读