Vue.js
Beginner
1 min read
onMounted and Template Refs
Example
<template>
<canvas ref="canvasEl" width="400" height="200"></canvas>
<input ref="inputEl" placeholder="Auto-focused" />
<!-- Child component ref -->
<ChildForm ref="childRef" />
<ul>
<!-- Template ref in v-for -->
<li v-for="item in items" :key="item.id" ref="listItems">
{{ item.name }}
</li>
</ul>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import ChildForm from './ChildForm.vue';
const canvasEl = ref(null);
const inputEl = ref(null);
const childRef = ref(null);
const listItems = ref([]);
const items = ref([
{ id: 1, name: 'Alpha' },
{ id: 2, name: 'Beta' },
]);
onMounted(() => {
// DOM element
inputEl.value.focus();
// Canvas 2D drawing
const ctx = canvasEl.value.getContext('2d');
ctx.fillStyle = 'royalblue';
ctx.fillRect(20, 20, 360, 160);
// Access exposed child method
childRef.value?.reset();
// Array ref from v-for
console.log('List items:', listItems.value.map(el => el.textContent));
});
</script>