Home > Blockchain >  How to call a function exposed via defineExpose when that component is rendered multiple times insid
How to call a function exposed via defineExpose when that component is rendered multiple times insid

Time:01-04

I have a Vue 3 component that exposes a function via defineExpose.

<template>
    ....
</template>
  
<script setup>
...

defineComponent({
  name: "SomeComponent"
});

function doStuff() {
  ... does stuff
} 

defineExpose({
  doStuff
});
</script>

That component is used in another component inside a v-for

<template>
  <div
    v-for="(item) in lst"
    ref="someComponentRefs"
  >
    <SomeComponent :attr="item" />
  </div>
</template>

<script setup lang="ts">
const lst = ref([1, 2, 3]);
const someComponentRefs = ref<Array<typeof SomeComponent>>([]);

function doStuffToItemOnIndex(index: number) => {
    const target = someComponentRefs.value[index];
    target.doStuff() // This won't work since target is a DOM node
}
</script>

According to this doc I need to add the ref attribute to the div that has the v-for. I can then use it to get the ref. What I want however is to pick a specific ref from the array and call the doStuff function on it. The way I do it now does not work since const target = someComponentRefs.value[index] returns a DOM node instead of a Ref.

How do I do this?

CodePudding user response:

The ref refers to the element that it is attached to. So you need to place it as the attribute of your component like so:

<div v-for="(item) in lst" >
    <SomeComponent ref="someComponentRefs" :attr="item" />
</div>
  • Related