2

Perhaps an obvious one, but I have a Vue Single File Component like this:

<template>
...
</template>

<script>
    export default {
        props: [ 'matches', 'results' ],

        computed: {

           formattedMatches: function () {
                let rows = [];
                this.matches.forEach(function($match, $i) {
                    rows[$i] = {
                        id: $i + 1,
                        title: $match[0] + ' ' + $match[1]
                    };
                });
                return rows;
            },

            formattedResults: function () {
                let rows = [];
                this.results.forEach(function($resultRow, $i) {
                    rows[$i] = {
                        id: $i + 1,
                        title: this.formattedMatches[$i]     
 // Error in render: "TypeError: Cannot read property 'formattedMatches' of undefined"
                    };
                });
                return rows;
            },
    ...
</script>

The error shows up also if I try with this.matches, not only with this.formattedMatches. I suppose it is a matter of variable scopes within classes and methods, but I do not even know if there is another better way or pattern to achieve that same behaviour.

Any ideas? Thanks in advance.

2 Answers 2

8

this has a different context in the anonymous function of forEach. Simplest fix is to use arrow function notation.

this.results.forEach(($resultRow, $i) => {
    rows[$i] = {
        id: $i + 1,
        title: this.formattedMatches[$i]
    };
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Stephen, it also works as expected. I have posted an equivalent solution right now.
2

Found the solution based on this other solution on StackOverflow. As it says, "this inside a callback refers to the callback itself (or rather, as pointed out, the execution context of the callback), not the Vue instance. If you want to access this you either need to assign it to something outside the callback".

So in my case...

...
formattedResults: function () {
     let self = this;
     let rows = [];
     this.results.forEach(function($resultRow, $i) {
         rows[$i] = {
              id: $i + 1,
              title: self.formattedMatches[$i]     
         };
     });
     return rows;
},
...

... does the trick. Thanks anyway!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.