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
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.
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!
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With