Skip to content

Instantly share code, notes, and snippets.

@M-Drummond
Last active March 3, 2024 10:00
Show Gist options
  • Save M-Drummond/c9e1179348311bf43a01d8c98ddbf032 to your computer and use it in GitHub Desktop.
Save M-Drummond/c9e1179348311bf43a01d8c98ddbf032 to your computer and use it in GitHub Desktop.
Vue - Computed property to filter an array of products.
export function filteredProducts() {
// get the total list of products
let filteredProducts = useGlobalStore().products;
// set criteria - examples var names here.
const stamina = useGlobalStore().decisions.stamina
const type = useGlobalStore().decisions.type
const group = useGlobalStore().decisions.group
const tags = useGlobalStore().selectedFilters
const time = useGlobalStore().selectedDuration
// Filter products based on criteria set above
if (stamina) {
filteredProducts = filteredProducts.filter(product => product[stamina]);
}
if (group) {
filteredProducts = filteredProducts.filter(product => product[group]);
}
if (type) {
filteredProducts = filteredProducts.filter(product => product[type]);
}
if (time) {
filteredProducts = filteredProducts.filter(product => product.prep_time <= time);
}
if (tags && tags.length > 0) {
filteredProducts = filteredProducts.filter(product => {
return tags.some(tag => product.tags.includes(tag));
});
}
// output a copy of the product list, less the items that do not match the filters.
return filteredProducts;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment