D
D
dicem2021-05-12 13:12:01
typescript
dicem, 2021-05-12 13:12:01

Why doesn't TypeScript allow DOM element methods for Vue Refs?

The error is actually in the method of the Vue component:

methods: {
...
  dropdownTrigger (e: Event | undefined) {
      if (e) {
        e?.stopPropagation()

        this.$refs.list.scrollTo(0, 0)
        this.isListVisible = !this.isListVisible
        if (!this.isListVisible) this.$refs.input.blur()
        this.selected = this.value
          ? [...this.value]
          : []
      }
  },
...
}

Error pointing to this.$refs.list.scrollTo(0, 0):
Property 'scrollTo' does not exist on type 'Vue | Element | Vue[] | Element[]'.
Property 'scrollTo' does not exist on type 'Vue'.ts(2339)


I use default Nuxt + TypeScript, there are 2 files in @types:
vue-shim.d.ts

declare module '*.vue' {
  import Vue from 'vue'
  export default Vue
}


tsx-shim.d.ts

import Vue, { VNode } from 'vue';

declare global {
  namespace JSX {
    interface Element extends VNode {}
    interface ElementClass extends Vue {}
    interface IntrinsicElements {
      [element: string]: any;
    }
  }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Yarkov, 2021-05-12
@dicem

Property 'scrollTo' does not exist on type 'Vue | element | vue[] | Element[]'

Well, it’s still written)) Type of ref Vue | Element | Vue[] | Element[]
If you know exactly what kind of element it is, then try this:
(this.$refs.list as HTMLDivElement).scrollTo(0, 0)

D
dicem, 2021-05-12
@dicem

Also a great solution in addition to Alexey Yarkov 's answer

import Vue, { VueConstructor, VNode} from 'vue'

interface Refs {
  $refs: {
    list: HTMLElement,
    input: HTMLInputElement,
  }
}

export default (Vue as VueConstructor<Vue & Refs>).extend({
  ...
  methods: {
    dropdownTrigger (e: Event | undefined) {
      this.$refs.list.scrollTo(0, 0) // наконец то отлично отрабатывает
    }
  }
  ...
})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question