1. 初始化項目
$ gridsome create my-blog
$ cd my-blog
$ gridsome develop
此時即可在 http://localhost:8080/
看到項目的首頁。
2. 安裝解析文件的插件
-
@gridsome/source-filesystem:將文件轉換爲
GraphQL
數據層可獲取的內容。 -
@gridsome/transformer-remark:
Gridsome
用於轉換Markdown
的轉換器。
安裝
$ cnpm install @gridsome/source-filesystem @gridsome/transformer-remark --save
在 gridsome.config.js 中配置插件
plugins: [
{
use: "@gridsome/source-filesystem",
options: {
path: "blog/*.md",
typeName: "Post"
}
}
]
插件的作用
@gridsome/source-filesystem
是將文件轉換爲可以在組件中使用 GraphQL
獲取的內容,而轉換的時候需要轉換器才能解析文件。因此需要安裝 @gridsome/transformer-remark
依賴。只要在 package.json
中找到支持文件的轉換器,Gridsome
就會自動轉換文件。
@gridsome/source-filesystem
的配置參數:
-
path
:文件的路徑。 -
typeName
:GraphQL
類型和模板名稱。src/templates
中的.vue
文件必須與typeName
匹配才能爲其具有模板。
3. 創建 markdown 文件的模版
在 templates
文件夾下新建 Post.vue
文件,該文件即所有 markdown
文件的模版頁面,所有的 markdown
文件會根據此文件的佈局渲染出頁面。
<template>
<Layout>
<div v-html="$page.post.content"/>
</Layout>
</template>
<page-query>
query ($id: ID!) {
post(id: $id) {
title
content
}
}
</page-query>
<script>
export default {
metaInfo() {
return {
title: this.$page.post.title
}
}
};
</script>
4. 創建 blog 文件夾
根據 @gridsome/source-filesystem
插件中的 path
定義的路徑,新建 blog
文件夾,本示例中安裝的目錄與 src
同級。
blog
文件夾中新建 test.md
文件。
---
title: Test
---
## 一個測試頁面
這是 **markdown** 文件的內容區,請在此將您出衆的思想分享給大家!
此時即可在 localhost:8080/blog/test
中看到該頁面了。
5. 在 index.vue 中添加跳轉鏈接
在 index.vue
中可添加跳轉至 blog
頁面的入口鏈接。
<template>
<Layout>
<h1>Hello, Gridsome!</h1>
<p v-for="edge in $page.posts.edges" :key="edge.node.id">
<a :href="edge.node.path">{{edge.node.title}}</a>
</p>
</Layout>
</template>
<page-query>
query {
posts: allPost{
edges {
node {
id
title
path
}
}
}
}
</page-query>
此時,就可以愉快的在 blog
中寫 markdown
文件了。
然而,gridsome
默認 markdown
文件是沒有樣式的,因此想要頁面有自己的特色,需要自定義 markdown
中不同語法的樣式,而欲知樣式如何定義,請聽下回分享。