There's no official way to declare the type for $refs in component options.
Indeed it seems you can avoid the type assertion by using either vue-class-component:
import Vue from 'vue'
import Component from 'vue-class-component'
@Component
export default class UserForm extends Vue {
$refs!: {
searchInput: HTMLFormElement
}
mounted() {
this.$refs.searchInput.reset()
}
}
or vue-property-decorator:
import { Vue, Component, Ref } from 'vue-property-decorator'
@Component
export default class UserForm extends Vue {
@Ref() readonly searchInput!: HTMLFormElement
mounted() {
this.searchInput.reset()
}
}
Alternatively, you can use the Composition API, declaring the type for the template ref:
import { defineComponent, ref, onMounted } from 'vue' // or `@vue/composition-api` for Vue 2
export default defineComponent({
setup() {
const searchInput = ref<HTMLFormElement>()
onMounted(() => searchInput.value?.reset())
return { searchInput }
}
})
demo