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);
}
}
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;
}
Source:stackexchange.com