deploy on Netli...
collections 是一群nodes節點的集合,很適合用來製作posts,tags,products列表的資料。可以讓graphQL裡面新增集合節點。有兩種方法可以新增collections:source plugin以及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-wordpress或是source-filesystem等套件載入,這裡使用source-filesystem舉例。
source-filesystem將本地文件轉換為可以使用GraphQL在組件中獲取的內容,一般會配合transformer-remark套件(把md文件轉換成html)的安裝。
-- source-filesystem
yarn add @gridsome/source-filesystemnpm install @gridsome/source-filesystem-- transformer-remark
yarn add @gridsome/transformer-remarknpm 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會出現兩個root在schema裡面,根據collection名稱actions.addCollection('Post')或是typeName: 'Post'的名稱建立兩種節點。
PostallPost而template用於為集合中的節點創建單個頁面。節點需要相應的頁面才能顯示在其自己的URL上。
屏東人,前端工程師,愛泰人。