Last active
January 21, 2021 09:21
-
-
Save smokeyfro/d9e9ba90f7e2da505d8c8e08f478961e to your computer and use it in GitHub Desktop.
Group posts by date 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 Year via computed</h1> | |
<ul> | |
<li v-for="(items, year) in groupedByYear" :key="year"> | |
{{ year }} | |
<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: { | |
// simple example to group by a simple field | |
// this examples uses the `groupBy` function which you can | |
// find in the `methods` section | |
groupedByYear() { | |
return this.groupBy( | |
this.$page.allBlogPost.edges, | |
'createdYear' | |
) | |
} | |
}, | |
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