Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add dynamic ref in vue.js?

Tags:

vue.js

I have some dynamic <input> elements in my dom rendered from for loop in vue. I need to add ref property to each of them by appending an Id to each ref like element1,element2,..etc. How to do this in vue?

<div v-for="(result, index) in data" :key="index">     <input type="text" type="file" ref="element" /> </div> 

How to add ref if result.id exists

like image 833
LJP Avatar asked Aug 08 '17 08:08

LJP


People also ask

How do I add to refs Vue?

We can add refs dynamically in our Vue. js app by assigning the ref prop to a dynamic value. We set the ref prop of each element to `element-${d.id}` . Then in the mounted hook, we get the this.

How do I access Vue refs?

Accessing the Refs Note that you can only access the ref after the component is mounted. If you try to access $refs. input in a template expression, it will be null on the first render. This is because the element doesn't exist until after the first render!

What is dynamic component in Vue?

Vue dynamic components enable users to switch between two or more components without routing, and even retain the state of data when switching back to the initial component. The central idea is to let users dynamically mount and unmount components in the user interface without using routers.

What is ref at Vue?

Refs are Vue. js instance properties that are used to register or indicate a reference to HTML elements or child elements in the template of your application. If a ref attribute is added to an HTML element in your Vue template, you'll then be able to reference that element or even a child element in your Vue instance.


1 Answers

Simply use v-bind like :ref="'element' + result.id" or ref="`element${result.id}`".

Check fiddle here.

new Vue({    el: '#app',    data: {      data: [{id: 1}, {id: 2}, {id: 3}],    },    mounted() {      console.log(this.$refs);    }  })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>    <div id="app">  <div v-for="(result, index) in data" :key="index">      <input type="text" type="file" :ref="'element' + result.id" />  </div>  </div>

Edited: Thanks to Vamsi's edit, I replaced index with result.id
Edited 8/28: Thanks to grokpot, I added a sample powered by Template literals.

like image 111
choasia Avatar answered Sep 25 '22 14:09

choasia