How to Fetch Additional Data in Page Modules

Follow

When using Page Modules, the fields of the module are passed down to the Vue component as props. However, you may run into a scenario where you want to fetch additional data into your Page Modules, such as information from a Content List or Item in Agility.

An example can be seen here on the Post Listing Page Module in the agilitycms-nuxtjs-starter.

What We'll Cover:

1. Fetching the Data

2. Making the Data Accessible 

3. Using the Data in your Page Module

Fetching the Data

In the ./src/data directory, create a file and use the $agilitycms global object to use the Agility CMS fetch methods:

export default async ({ $agility }) => {
  // set up posts array
  let posts = [];

  // set language code
  const languageCode = $agility.languages[0];

  try {
    // raw posts
    const rawPosts = await $agility.client.getContentList({
      referenceName: "posts",
      languageCode,
    });

    // categories
    const categories = await $agility.client.getContentList({
      referenceName: "categories",
      languageCode,
    });

    posts = rawPosts.map((post) => {
      // get category id
      const categoryID = post.fields.category?.contentid;

      // find matching category
      post.linkedCategory = categories?.find((c) => c.contentID == categoryID);

      // format date
      post.formattedDate = new Date(post.fields.date).toLocaleDateString();

      // return post
      return post;
    });
  } catch (error) {
    if (console) console.error("Could not load posts list.", error);
  }

  return posts;
};

PostListing.js

Making the Data Accessible

Once you've fetched your data, import it into the agility.components.js file and add it to the dataFetch object:

// Our Agility Data Fetch
import PostsListingData from "./data/PostsListing";

export default {
  dataFetch: {
    PostsListing: PostsListingData,
  },
  moduleComponents: {
    ...
  },
  pageTemplateComponents: {
    ...
  },
};

agility.components.js

Using the Data in your Page Module

To use the Data in your Page Module, return the moduleData in the Page Module computed object:

<template>
  <ul v-for="post in posts">
   <li>{{ post.fields.title }}<li>
  <ul>
<template>
<script> export default { props: { contentID: Number, item: Object, page: Object, pageInSitemap: Object, dynamicPageItem: Object, moduleData: Object, }, computed: { posts: function() { // our module data was loaded in src/data/PostsLists.js return this.moduleData["PostsListing"]; }, }, }; </script>

PostsListing.vue

1 out of 1 found this helpful

Comments

0 comments

Please sign in to leave a comment.