# $refs
类型扩展
组件的 $refs
类型被声明为最广泛的类型,以处理所有可能的 ref 类型。虽然理论上是正确的,但在大多数情况下,每个 ref 在实践中只包含一个特定的元素或组件。
您可以通过在类组件中覆盖 $refs
类型来指定特定的 ref 类型
<template>
<input ref="input">
</template>
<script lang="ts">
import Vue from 'vue'
import Component from 'vue-class-component'
@Component
export default class InputFocus extends Vue {
// annotate refs type.
// The symbol `!` (definite assignment assertion)
// is needed to get rid of compilation error.
$refs!: {
input: HTMLInputElement
}
mounted() {
// Use `input` ref without type cast.
this.$refs.input.focus()
}
}
</script>
您可以在上面的示例中访问 input
类型,而无需类型转换,因为 $refs.input
类型是在类组件上指定的。
请注意,它应该是类型注释(使用冒号 :
)而不是值赋值(=
)。