5

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?

2 Answers 2

9

you can use the [] notation:

  methods: {
    foo (id) {
        alert(this.$refs[id + '-test'].innerText)
    }
  }

A complete working example: https://jsfiddle.net/drufjsv3/2/

Sign up to request clarification or add additional context in comments.

1 Comment

adding to this, if you are using this inside a bunch of components made using v-for with dynamic refs, you will need to use this.$refs[id + '-test'][0].innerText to access anything in that component vuejs.org/v2/api/#ref
1

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;
            });
        },
.....

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.