Building an E-Commerce Store - Browsing Products Chapter 10
Wiring up the ordering
With our price readily available, we can proceed with wiring up the ordering. Create a new
computed function titled orderProducts that returns this.products. We want to
ensure we are always sorting from the source and not ordering something that has
previously been ordered. Call this new function from within the paginate function and
remove the parameter from this method and from the template:
computed: {
...
orderProducts() {
return this.products;
},
},
methods: {
paginate() {
return this.orderProducts.slice(
this.pagination.range.from,
this.pagination.range.to
);
},
}
To determine how we need to sort the products, we can use the this.ordering value. If it
exists, we can split the string on the hyphen, meaning we have an array containing the field
and order type. If it does not exist, we need to simply return the existing product array:
orderProducts() {
let output;
if(this.ordering.length) {
let orders = this.ordering.split('-');
} else {
output = this.products;
}
return output;
}
Sort the products array based on the value of the first item of the ordering array. If it is a
string, we will use localCompare, which ignores cases when comparing. Otherwise, we
will simply subtract one value from the other – this is what the sort function expects:
orderProducts() {
let output;