Search code examples
arraysmethodsforeachvue.jscomputed-properties

Access returned computed array within method and manipulate


I have a computed array which is full of tags and updates depending on what selection i make in the select box. I would like to take this array and pass it to a method and then run a method to update what “results” have an active class. Although I get an array saying I can’t run forEach on this element.

Been through a few topics and understand computed properties dont work like that but surely there is a way around this.

https://jsfiddle.net/39jb3fzw/6/

Short Snippet

methods: {
        updateOutput() {
          var tags = this.tagArray;
          tags.forEach(function(tag) {
            console.log(tag);
          })
        }
    },
    computed: {
        concatenated: function () {
            var ret = this.selected.concat(this.selected2, this.selected3);
            this.tagArray = ret;
            //this.updateOutput();
            return ret;
        }
    }

Full Output

https://jsfiddle.net/39jb3fzw/6/

Thanks again :slight_smile:


Solution

  • It looks like the issue is the line:

    var ret = this.selected.concat(this.selected2, this.selected3);

    That line of code is returning an empty string rather than an array. This is because this.selectedX is a string rather than an Array. This explains why tag.forEach is undefined. forEach doesn't exist on the String prototype.

    You can create this an array instead be doing

    var ret = [ this.selected, this.selected2, this.selected3 ]

    From there you can set this.tagArray to ret

    Hope this helps