How to filtering content using relation in @nuxt/content

Category:
Author: zemna
Date: April 17, 2021
Share this:

Maybe your site article has relation with categories and tags.

This tutorial shows how to filtering articles by tag.

Add tag content files to content folder

---
name: Test
description: This is test tag
---

Add tags front matter to content

---
title: This is test post
tags:
  - Test
  - Nuxt
---

This is test post. Hello World.

Create tags/_slug/index.vue file

Add where clause to filtering articles by selected tag.

<template>
  <div>
    <!-- Your html code -->
  </div>
</template>

<script>
export default {
  async asyncData({ $content, params }) {
    const tag = await $content('tags', params.slug).fetch()
    const articles = await $content('articles')
      .only(['title', 'description', 'img', 'slug', 'tags'])
      .where({ 'tags': { $contains: tag.name } })
      .sortBy('createdAt', 'asc')
      .fetch()

    return {
      tag,
      articles
    }
  }
}
</script>
Share this:

Leave a Reply

Your email address will not be published. Required fields are marked *

Let's connect and create
something awesome together!
2023 - Copyright, All Rights Reserved, Made by ZEMNA.NET with ❤️
crossmenu linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram