vue: v-ref inside v-for is not defined

When using v-ref on a component with v-for it produces a list of components. But, when using components inside a v-for and using v-ref on this component, I expect the same behavior but the component list is not present in $refs.

See this code sample illustrating the issue with Vue.js 1.0.11: https://jsfiddle.net/noirbizarre/jms2gzpt

I think this is related to #1850 and to #1697

About this issue

  • Original URL
  • State: closed
  • Created 9 years ago
  • Reactions: 9
  • Comments: 15 (2 by maintainers)

Most upvoted comments

@yyx990803 I have the same problem. And I think you should let developers decide how to name for v-ref. Developer will solve the conflict of v-ref name. Let’s see below code. Situation 1:

<div v-for="item in items">
  <comp v-ref:nested{{item}} :value="item"></comp>
</div>

We can use $refs.nested{{index}} to name them.

Situation 2:

<div v-for="item in items">
  <div v-for="sub in item.subs">
    <comp v-ref:nested{{item.sub}}></comp>
  </div>
</div>

What we need to do is add a feature to make v-ref accept variable. How about that?

@MrPhilipT I use

this.$el.querySelector(`[name="whatever-${index}"]`)

😉

As an example, this is how I worked around the problem:

<tr v-for="contract in contracts" :key="contract.id">
   <td>
        <button @click="showModal(contract)">Edit</button>

        <contract-modal :contract="contract" ref="modals"></contract-modal>

[...]

    showModal(contract) {
        this.$refs.modals.find(ref => ref.contract.id === contract.id).show = true;
    },


Note that the component ContractModal in this example has a boolean property show, which controls the visibility of the modal. The essence of this example is the call to this.$refs.modals.find() that fetches the component from the array.

Well, I probably misunderstood… Sorry about that

I agree with @zyf0330. Dynamic v-ref’s could be really useful. For example, if you have multiple instances of a component and you want to track one down and call a method on it, a unique id can be assigned to each component as a required prop, which can then be used by the consumer to easily fetch it, without having to hunt it down the tree.

E.g, i’ve built a pagination component which accepts a ‘for’ prop:

  <pagination for="table2" per-page="25" records="100"></pagination>

would be nice if the consumer could do something like

this.$refs.table2.setPage(1)