Reputation: 2578
I am trying to access a DOM element with Vue, using the $refs
functionality, but I am having trouble getting it to work.
My element looks like so below. The plateId is generated dynamically, so it will not always be the same number:
<textarea :ref="plateId + '-notes'">
My Vue function looks like so:
/* This does not work */
addNotes: function(plateId) {
console.log(this.$refs.plateId + '-notes');
}
Whenever I run this code and the function is activated, it just reads undefined
in my console. I've also tried this, which also does not work and reads undefined:
/* This does not work */
addNotes: function(plateId) {
var plateIdNotes = plateId + '-notes';
console.log(this.$refs.plateIdNotes);
}
Replacing var
with const
(I am using ES6 and transpiling the code) doesn't work either:
/* This does not work */
addNotes: function(plateId) {
const plateIdNotes = plateId + '-notes';
console.log(this.$refs.plateIdNotes);
}
I know the ref
is binding correctly to the element, because when I do this below, I can see all of my other refs in the console, as well as the plateId-notes ref:
/* This works */
addNotes: function(plateId) {
console.log(this.$refs);
}
How can I access the plateId
ref using the parameter in my function?
Upvotes: 5
Views: 13226
Reputation: 367
also, you can acces to all the $refs rendered in view by accessing
vm.$children.forEach( child => {
var tag = child.$vnode.data.ref;
console.log(vm.$refs[tag]);
vm.$refs[tag].loadData();
});
// loadData() is a method to implement when mounted or when you want to reload data
////////////////////////////////////
<script>
export default {
data() {
return {
notifications: []
}
},
mounted() {
this.loadData();
},
methods: {
loadData: function() {
axios.get('/request-json/notifications').then(res => {
this.notifications = res.data;
});
},
.....
Upvotes: 1
Reputation: 16344
you can use the []
notation:
methods: {
foo (id) {
alert(this.$refs[id + '-test'].innerText)
}
}
A complete working example: https://jsfiddle.net/drufjsv3/2/
Upvotes: 9