Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Ajvanho's avatar
Level 14

weird refs in Vue 3

I read the recommendations not to use document query selectors in vue.js. We need to use refs, but it is weak documentation to do such a simple thing, for example:

//template
<input ref="inputField" type="number">
<button @click="fire(id)" type="button">Button</button>

//script setup
function fire (i) {
        document.querySelectorAll('input')[i].classList.add("hidden")
 }

This is working, but how can I do this with refs?

0 likes
4 replies
Sergiu17's avatar
<input ref="inputField" type="number">
<button @click="fire('inputField')" type="button">Button</button>

function fire (i) {
	this.$refs[i].classList.add('hidden');
 }
1 like
JeffreyWay's avatar

If you're using script setup, then:

<template>
    <input ref="input" type="number">
    <button @click="fire" type="button">Button</button>
</template>
import {ref} from 'vue';

let input = ref(null);

function fire() {
    input.value.classList.add("hidden")
 }

That said, not sure what you're doing here, but I probably wouldn't resort to manually editing the classList.

1 like
Sergiu17's avatar

@Ajvanho add a new property to your list of inputs

<template>
    <section v-for="input in inputs" :key="input.id">
        <label>
            {{ input.name }}
            <input :class="{ 'hidden': input.hidden }"/>
        </label>
        <button @click="fire(input)">Click</button>
        <input type="checkbox" v-model="input.hidden">
    </section>
</template>

<script setup>
import { ref } from 'vue';

let inputs = ref([
    {id: 1, name: 'Name', hidden: false},
    {id: 2, name: 'Email', hidden: false},
]);

function fire(input) {
    input.hidden = true;
}
</script>
1 like

Please or to participate in this conversation.