Czasem potrzebujesz bezpośredniego dostępu do elementu DOM - jak inżynier, który musi sprawdzić fizyczny sensor.
1<template>
2 <div class="input-panel" style="background: #0a0e27; padding: 1rem;">
3 <input ref="inputRef" type="text" placeholder="Kod modułu"
4 style="background: #0a0e27; border: 1px solid #00b4d8; color: #00ff88; padding: 0.5rem;">
5 <button @click="focusInput" class="btn-focus">Ustaw fokus</button>
6 </div>
7</template>
8
9<script setup>
10import { ref, onMounted } from 'vue'
11
12// Nazwa musi odpowiadać atrybutowi ref w template
13const inputRef = ref(null)
14
15function focusInput() {
16 inputRef.value?.focus()
17}
18
19onMounted(() => {
20 // Element jest dostępny po zamontowaniu
21 inputRef.value?.focus()
22})
23</script>1<template>
2 <div class="modules-list">
3 <ul style="list-style: none; background: #0a0e27;">
4 <li v-for="module in modules" :key="module.id" ref="itemRefs"
5 style="color: #00b4d8; padding: 0.5rem; border-left: 2px solid #00ff88;">
6 {{ module.name }}
7 </li>
8 </ul>
9 </div>
10</template>
11
12<script setup>
13import { ref, onMounted } from 'vue'
14
15const modules = ref([
16 { id: 1, name: 'Oxygen Generator' },
17 { id: 2, name: 'Water Recycler' }
18])
19
20const itemRefs = ref([])
21
22onMounted(() => {
23 console.log(itemRefs.value) // Tablica elementów LI
24})
25</script>1<template>
2 <input :ref="setInputRef" type="text"
3 style="background: #0a0e27; border: 1px solid #00ff88; color: #00b4d8;">
4</template>
5
6<script setup>
7import { ref } from 'vue'
8
9const dynamicRef = ref(null)
10
11function setInputRef(el) {
12 dynamicRef.value = el
13 console.log('Element ustawiony:', el)
14}
15</script>1<template>
2 <SensorPanel ref="sensorRef" />
3</template>
4
5<script setup>
6import { ref, onMounted } from 'vue'
7import SensorPanel from './SensorPanel.vue'
8
9const sensorRef = ref(null)
10
11onMounted(() => {
12 // Dostęp do metod i właściwości komponentu
13 sensorRef.value?.refreshData()
14})
15</script>
16
17<!-- SensorPanel.vue - musi eksponować metody -->
18<script setup>
19import { ref } from 'vue'
20
21const sensorData = ref({})
22
23function refreshData() {
24 console.log('Odświeżanie danych z sensorów!')
25}
26
27// Expose - udostępnij rodzicowi
28defineExpose({
29 refreshData,
30 sensorData
31})
32</script>