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

mpk123's avatar

Dynamic Refs

Can someone please help me understand dynamic refs in Vue3? I have a group of radio buttons and trying to return the value of the selected button. In the code below the same value is returned regardless of which button I click.

<script setup> 

const props = defineProps({       
    mealServices: Array,
});

const activeMealService = ref([])

const setActiveMealService = () => {
        console.log('meal id is ' + activeMealService)
};

</script>
<div v-for="mealService in mealServices" :key="mealService.id">

		<input  type="radio" name="meal_type" @click="setActiveMealService"  
				:ref="(el) => {activeMealService = mealService.meal_type_id}" 
				:id="mealService.meal_type_id" 
				:value="mealService.meal_type_id" 
				v-model="form.meal_type_id"/>
                                
		<label :for="mealService.meal_type_id">{{ mealService.meal_type.name }}</
</div>
0 likes
2 replies
martinbean's avatar

@mpk123 I don’t really understand what you’re trying to do with the ref in the first place. You don’t need it. You should be using v-model as you are. So long as each radio input has the same name attribute value, then the selected value will be available as the v-model value:

<template>
    <div v-for="mealService in mealServices" :key="mealService.id">
        <input
            :id="`meal-service-${mealService.meal_type_id}`"
            name="meal_service"
            type="radio"
            :value="mealService.meal_type_id"
            v-model="selectedMealService"
        />
        <label :for="`meal-service-${mealService.meal_type_id}`">{{ mealService.meal_type.name }}</label>
    </div>
</template>

<script setup>
const props = defineProps({
    mealServices: Array,
});

const selectedMealService = ref();
</script>

As you see, there’s no need for refs or on click handlers as that’s what v-model is for.

mpk123's avatar

Im trying to pass the value of the clicked on radio into a function. Im just using console log log to keep it simple. When i remove the ref i get the current value. Not the clicked on value.

Please or to participate in this conversation.