JANE'S BLOG


gridsome collections 介紹

collections 是一群nodes節點的集合,很適合用來製作posts,tags,products列表的資料。可以讓graphQL裡面新增集合節點。有兩種方法可以新增collections:source plugin以及data store API

data store API

gridsome.server.js檔案裡面的api.loadSource

  • 利用actions.addCollection('Post')新增集合。
  • 利用collection.addNode(obj)新增node節點。
// gridsome.server.js
const axios = require('axios')

module.exports = function (api) {
  api.loadSource(async actions => {
    const collection = actions.addCollection('Post')

    const { data } = await axios.get('https://api.example.com/posts')

    for (const item of data) {
      collection.addNode({
        id: item.id,
        title: item.title,
        content: item.content
      })
    }
  })
}

source plugin

使用source-wordpress或是source-filesystem等套件載入,這裡使用source-filesystem舉例。

source-filesystem將本地文件轉換為可以使用GraphQL在組件中獲取的內容,一般會配合transformer-remark套件(把md文件轉換成html)的安裝。

安裝

-- source-filesystem

  • yarn add @gridsome/source-filesystem
  • npm install @gridsome/source-filesystem

-- transformer-remark

  • yarn add @gridsome/transformer-remark
  • npm install @gridsome/transformer-remark

用法

一般來說這兩個套件會一起用,用法如下:

// gridsome.config.js
module.exports = {
  plugins: [
    {
      use: '@gridsome/source-filesystem',
      options: {
        path: 'blog/**/*.md',
        typeName: 'Post',
        remark: {
          // remark options
        }
      }
    }
  ],
  transformers: {
    remark: {
      // global remark options
    }
  }
}

使用

根據path在底下建立blog資料夾放置.md的檔案。

Collections in GraphQL

每一個collections會出現兩個root在schema裡面,根據collection名稱actions.addCollection('Post')或是typeName: 'Post'的名稱建立兩種節點。

  • node 節點: Post
  • a list of nodes 節點集合: allPost

template用於為集合中的節點創建單個頁面。節點需要相應的頁面才能顯示在其自己的URL上。

KEYWORDS
gridsome

ABOUT ME


Jane

屏東人,前端工程師,愛泰人。

LATEST


INSTAGRAM