Here's a short tutorial on using Vue.js3 template refs inside v-for
to call child component methods with the Composition API.
Assuming you want to invoke the reset function of each child component, you can accomplish this as follows:
App.vue
<script setup>
import { ref } from 'vue'
import Comp from './Comp.vue'
import Comp1 from './Comp1.vue'
const compRefs = ref([])
function onReset() {
compRefs.value.forEach(comp => comp.onReset())
}
</script>
<template>
<div v-for="n of [0, 1, 2]">
<template v-if="0 === n % 2">
loop {{n}}: <Comp ref="compRefs"></Comp>
</template>
<template v-if="1 === n % 2">
loop {{n}}:<Comp1 ref="compRefs"></Comp1>
</template>
</div>
<button @click="onReset">
Reset
</button>
</template>
Comp.vue
<script setup>
import { ref } from 'vue'
const msg = ref('')
function onReset() {
msg.value = 'Reset is activated'
}
defineExpose({ onReset })
</script>
<template>
<div>
Child COM {{ msg ? ':' + msg : '' }}
</div>
</template>
Comp1.vue
<script setup>
import { ref } from 'vue'
const msg = ref('')
function onReset() {
msg.value = 'Reset is activated'
}
defineExpose({ onReset })
</script>
<template>
<div>
Child COM1 {{ msg ? ':' + msg : '' }}
</div>
</template>
Please note that the function you want to invoke must be exposed and the template ref should be placed on the child component, rather than on the div where the v-for directive is specified. This is because we need to access the function of the child component.
You can checkout the code on this playground.
That's all, Enjoy!
Top comments (0)