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

dcranmer's avatar

Ref is an array?

I've got a form fieldset of checkboxes ("areas") in a blade file. Each area has an id and a name, and the areas are stored as an array of objects in a Vuex store. When I loop through the areas array using v-for, I am assigning a ref to each checkbox input. What's puzzling me is why each ref is itself an array. I've never seen that before. So in order to, say, move the focus to the first checkbox, I need to write

this.$refs.area_1[0].focus()

Which feels odd. I must be missing something -- can anyone explain this?

Here is the loop:

<div v-for="area of areaSet">
    <input
       type="checkbox"
       name="area_id[]"
       :value="area.id"
       v-model.number="$v.form_areas.$model"
       :id="'area_' + area.id"
       :ref="'area_' + area.id"
      >
    <label :for="'area_' +area.id" class="checkbox">
       @{{ area.area_name }}
    </label>
 </div>

In Vue Devtools, the relevant $refs are listed like this:

area_1:Array[1]
0:<input id="area_1">
area_10:Array[1]
0:<input id="area_10">
area_11:Array[1]
0:<input id="area_11">
area_2:Array[1]
0:<input id="area_2">
area_3:Array[1]
0:<input id="area_3">
0 likes
4 replies
dcranmer's avatar

Edit:

If I generate the refs within a component instead of within a blade file (which uses the root Vue instance), they are no longer arrays. Each instance of the component has a single ref that is the referenced html element; e.g.,

area_1:<input id="area_1" class="area-checkbox">

I kinda see what's happening, but I'm not 100% sure why it works this way.

EndEdit

Hmm. This is interesting. I'm curious: what is it that makes some refs an array (above) and others not? Is it that the refs in both of our examples are generated dynamically? I have a whole bunch of refs that are not arrays; they are just the relevant html element. e.g.,

admin_notes_input:<textarea id="admin_notes_input" class="textarea">
allCountiesCheckbox:<wi-allcountiescheckbox>
city_town_area_input:<textarea id="city_town_area_input">
description_input:<textarea id="description_input" class="textarea">
editorCombobox:<wi-autocomplete id="editor_input">
firstFocus:<input id="firstName" class="input">
leaderCombobox:<wi-autocomplete id="leader_input">
leaderModal:<wi-modal>
SteveEdson's avatar

For anyone finding this thread later on, it's because the ref sits within a v-for loop. Vue changes the ref to an array, because there could be multiple elements being referenced. Likewise, when the the ref sits within the component, each component has its own scope, so its a single ref, rather than an array.

Hope this helps!

4 likes

Please or to participate in this conversation.