【问题标题】:What type is a Vue 3 template function ref?Vue 3 模板函数 ref 是什么类型?
【发布时间】:2022-07-21 15:22:44
【问题描述】:
Vue 3 允许使用函数来分配引用
const target = ref<Element>()
const functionRef = (ref: Element) => {
target.value = ref
}
<template>
<div :ref="functionRef" />
</template>
但是,Volar 和 TypeScript 都会抱怨 :ref="functionRef" 绑定类型不匹配。
Type '(ref: Element) => void' 不可分配给 type 'string |参考 | ((参考:Element | ComponentPublicInstance> | null) => void) |未定义'。
runtime-dom.d.ts(1479, 3):预期类型来自属性“ref”,该属性在此处声明为“ElementAttrs”类型
函数 ref 的类型是什么?
【问题讨论】:
标签:
vue.js
vuejs3
vue-sfc
【解决方案1】:
runtime-dom.d.ts 链接包含以下定义。
type ReservedProps = {
key?: string | number | symbol
ref?:
| string
| RuntimeCore.Ref
| ((ref: Element | RuntimeCore.ComponentPublicInstance | null) => void)
ref_for?: boolean
ref_key?: string
}
此定义可在源代码here 中找到。
重要的部分是ref? 的第三个联合类型
(ref: Element | RuntimeCore.ComponentPublicInstance | null) => void
这意味着您可以为ref 参数定义一个可重用的类型,如下所示。
// this may not be necessary depending on where you put this definition
import * as RuntimeCore from '@vue/runtime-core'
type VueRef = ref: Element | RuntimeCore.ComponentPublicInstance | null) => void
您现在可以使用 arg 的新类型更新函数 ref
const target = ref<Element>()
const functionRef = (ref: VueRef) => {
target.value = ref
}
【解决方案2】:
import { ComponentPublicInstance } from 'vue';
const functionRef = (ref: ComponentPublicInstance | null | Element) => {
target.value = ref
}
<div :ref="functionRef" />