Last active
January 21, 2021 09:20
-
-
Save smokeyfro/320f28ed9a0176c9ca9f1442044b1d95 to your computer and use it in GitHub Desktop.
Group posts by category with method & computed property
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template> | |
<Layout> | |
<h1>Group by Category via computed</h1> | |
<ul> | |
<li v-for="(items, category) in groupedByCategory" :key="category"> | |
{{ category }} | |
<ul> | |
<li v-for="item in items" :key="item.id"> | |
{{ item.title }} | |
</li> | |
</ul> | |
</li> | |
</ul> | |
</Layout> | |
</template> | |
<script> | |
export default { | |
metaInfo: { | |
title: 'Hello, world!' | |
}, | |
computed: { | |
// group by category title | |
// to show how to use child object properties | |
groupedByCategory() { | |
return this.groupBy( | |
this.$page.allBlogPost.edges, | |
function(node) { | |
return node.category.title; | |
} | |
) | |
} | |
}, | |
methods: { | |
/*! | |
* Group items from an array together by some criteria or value. | |
* (c) 2019 Tom Bremmer (https://tbremer.com/) and Chris Ferdinandi (https://gomakethings.com), MIT License, | |
* @param {Array} arr The array to group items from | |
* @param {String|Function} criteria The criteria to group by | |
* @return {Object} The grouped object | |
*/ | |
groupBy(arr, criteria) { | |
return arr.reduce(function (obj, item) { | |
// set the node element as item | |
// otherwise we have to use `item.node` everywhere in the code | |
item = item.node; | |
// Check if the criteria is a function to run on the item or a property of it | |
var key = typeof criteria === 'function' ? criteria(item) : item[criteria]; | |
// If the key doesn't exist yet, create it | |
if (!obj.hasOwnProperty(key)) { | |
obj[key] = []; | |
} | |
// Push the value to the object | |
obj[key].push(item); | |
// Return the object to the next item in the loop | |
return obj; | |
}, {}); | |
} | |
} | |
} | |
</script> | |
<page-query> | |
query { | |
allBlogPost { | |
edges { | |
node { | |
id | |
title | |
createdYear: created(format: "Y") | |
created | |
category { | |
title | |
} | |
} | |
} | |
} | |
} | |
</page-query> | |
<style> | |
.home-links a { | |
margin-right: 1rem; | |
} | |
</style> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment