在 Vue 3 + TypeScript + Options API 中使用 refs

问题描述 投票:0回答:3

我试图了解将 refs 与 TypeScript 和 Options API 一起使用的最佳方法。 在文档中他们像下面一样引用它,但是没有使用 TS。当谈到 TS 时,他们只解释了如何使用 Composition API。

当我使用

this.$refs.myRef
时,它会抛出此错误
Object is of type 'unknown'.

我知道我可以像这样投射和使用它:

(this.$refs.myRef as HTMLElement)
但我觉得没有必要每次都为每个裁判都这样做。

通过 Options API + TS 使用参考的正确方法是什么?

vue.js
3个回答
8
投票

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

shims-runtime-core.d.ts

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

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

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


0
投票

我尝试在子组件上使用

ref
来调用触发函数,因为使用 props 和观察者对于这么简单的事情感觉太复杂了。

添加子组件并在模板中添加

ref

<ChildComponent ref="childComponent"></ChildComponent>

我只暴露了触发函数:

export default {
    name: "ChildComponent",
    expose: ['someFunction'],  
    methods: {
        someFunction() {
        // …
      },
    },
}

在此处查看更多内容:https://vuejs.org/guide/essentials/template-refs.html#ref-on-component

然后我尝试在模板中这样使用它

<something v-on:click="($refs.childComponent as typeof ChildComponent).someFunction()"></something>

就像这样的方法

this.$refs.childComponent.someFunction();

尽管我从 volar 得到了这两个错误: 用于模板中

错误 TS18046:“__VLS_ctx.$refs.childComponent”的类型为“未知”

以及在方法中的使用

错误 TS2571:对象的类型为“未知”

所以我尝试在这两个地方添加类型信息

($refs.childComponent as typeof ChildComponent)

这在模板中不起作用,您将收到此错误:

错误 TS2339:类型上不存在属性“ChildComponent”...

<something v-on:click="($refs.childComponent as typeof ChildComponent).someFunction()"></something>

解决方案

但在这种方法中,由于某种原因它工作得很好

methods: {
  callChildMethod() {
    (this.$refs.childComponent as typeof ChildComponent).someFunction();
  },
}

所以你需要将触发函数包装在一个方法中,然后可以在模板中调用

<something v-on:click="callChildMethod()"></something>

0
投票

找不到更好的解决方案:

type Refs = {
  input: HTMLInputElement;
}

(this.$refs as Refs).input.focus();

© www.soinside.com 2019 - 2024. All rights reserved.