Search code examples
vue.jsvuejs2computed-properties

Vuejs: Can't access (computed) props within computed property loop


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.


Solution

  • 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!