简体   繁体   中英

Using Vue $refs dynamically inside of function with parameter

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?

you can use the [] notation:

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM