[Vuejs]-Can't reach data variable inside function?

0πŸ‘

βœ…

To use the property specified by filterOption, you’ll have to use bracket notation:

// if (a.filterOption < b.filterOption) ❌ object does not contain property named "filterOption"
if (a[filterOption] < b[filterOption])  βœ… lookup property specified by `filterOption`

Also note that Array.prototype.sort() mutates the original array, which Vue will warn you about. Use Array.prototype.slice() beforehand to avoid this mutation:

// return this.albums.sort(compare);       ❌ mutates original array
return this.albums.slice().sort(compare);  βœ… mutates copy

The resulting code should look like this:

computed: {
  sortedArray: function() {
    const filterOption = this.filterOption
    function compare(a, b) {
      if (a[filterOption] < b[filterOption])
        return -1;
      if (a[filterOption] > b[filterOption])
        return 1;
      return 0;
    }

    return this.albums.slice().sort(compare);
  }
}

demo

0πŸ‘

As filterOption is a data object property, You can not directly access this in computed. You have to access this with a scope (this). Hence, it should be :

function compare(a, b) {
    if (a[this.filterOption] < b[this.filterOption])
        return -1;
    if (a[this.filterOption] > b[this.filterOption])
        return 1;
    return 0;
}

Leave a comment