Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use Vue Custom Directives with Typescript

I am trying to understand how to convert the example below using typescript and the Composition API, with the setup script. This example it from the vue documentation. I don’t know what type to give the "el" parameter to get this to work.

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In Vue 3, components are no longer limited to only 1 root element. Implicitly, this means you no longer have an this.$el. You can create one by adding ref="" to DOM element you want to target.

<script setup lang="ts">
// enables v-focus in templates
const root = ref(null)

onMounted(() => {
    // here you got root $el
    root.value.focus()
})

// Using Option API. I didn't check are it works.
this.$refs.$el
</script>

<template>
  <input ref="root" />
</template>

In composition API it will be like that:

<script setup lang="ts">
// enables v-focus in templates
const vFocus = {
  mounted: (el: any) => el.focus()
}
</script>

<template>
  <input v-focus />
</template>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading