giannicash
giannicash

Reputation: 11

Get template ref in Vue Composable Function

I need to get a template ref in a Vue Composable Function in a Nuxt project.

My template is:

// /components/Component.vue

<template>
  <div ref="element">
    ...
  </div>
</template>

I tried to get the ref by declare it on the composable function:

// /composables/useComposable.js

export const useComposable = () => {
  const element = ref(null)
  ...
}

And I also tried to declare it on the setup:

// /components/Component.vue

<script setup>
const element = useRef(null)

useComposable(element.value)
</script>

It's not working in both cases. It only works in the second case but only if I wrap the useComposable in the onMounted hook. Is there any chance to get the result without using the onMounted hook?

Upvotes: 0

Views: 1279

Answers (1)

Thomas
Thomas

Reputation: 7080

Pass in the ref itself and not the .value. You lose reactivity with that and at the time you put it into the composable it is still null.

Composable:

export const useComposable = (element: Ref<HTMLDivElement>) => {
    //use it with element.value in here
}

Component:

<script setup>
import { ref } from 'vue'

const element = ref(null)
useComposable(element)
</script>
<template>
  <div ref="element">
    ...
  </div>
</template>

Upvotes: 2

Related Questions