DEV Community

Ken Ng
Ken Ng

Posted on

3

Vuejs3 Template Refs inside v-for

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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!

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay