Home > database >  can't reach data variable inside function?
can't reach data variable inside function?

Time:04-13

I got a computed function that sorts my array, it works good until i wanna be able to sort it after a variable.

Heres how it looks right now:

data: function ()  {
  return {
     closeOnClick: true,
      filterOption: 'title',
  }

my actual function here

computed: {

    sortedArray: function() {
      function compare(a, b) {
        if (a.filterOption < b.filterOption)
          return -1;
        if (a.filterOption > b.filterOption)
          return 1;
        return 0;
      }

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

Whenever i do console.log(this.filterOption) it does display the correct value, but for some reason its not filtering after what i want. If i do however type manually in for an example if (a.title < b.title) instead of trying to use the variable, the filtering works magic.

Any ideas why i cant use the variable as im expecting to?

CodePudding user response:

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

CodePudding user response:

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;
}
  • Related