1980's Maker

一个出生于80年代的程序员 -- 喜爱创[客]、美[食]、动[画]、怀[旧]的新手艺人的博客

VuePress主题教程 --SubNav模板编写

SideBar是一个复合模板, FooterBar,NavBar, SubNav均包含在里面, 我们已经完成了NavBar, 剩下的SubNav是对站点的分类、标签及文章的简易统计和快速入口,FooterBar是用来放一些社交媒体链接及版权信息。

我们先来编写SubNav模板,想下可以从哪里获取这些统计数据,没错,还是blog插件君.

在他的加持下,只需简单的三步便可完成我们想要的功能。

  1. 添加插件配置:



















 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 





// .vuepress/theme/index.js
module.exports = (themeConfig, ctx) => {
  return {
    // ...
    plugins: [
      [
        '@vuepress/blog',
        {
          directories: [
            {
              id: 'post',
              dirname: '_post',
              path: '/'
            }
          ],
          globalPagination: {
            lengthPerPage: 5,
          },
          frontmatters: [
            {
              id: "tag",
              keys: ['tag', 'tags'],
              path: '/tags/',
              frontmatter: { title: 'Tag' },
              pagination: {
                lengthPerPage: 10
              }
            },
            {
              id: "category",
              keys: ['category', 'categories'],
              path: '/categories/',
              frontmatter: { title: 'Category' },
              pagination: {
                lengthPerPage: 10,
                prevText: '',
                nextText: ''
              }
            }
          ]
        }
      ]
    ]
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
  1. 给文章添加frontmatter字段:



 
 
 
 
 


---
date: 2021-03-11
title: two
category: theme
tags:
  - course
  - vuepress
---
## two 
1
2
3
4
5
6
7
8
9


 
 
 
 



---
date: 2021-03-03
categories:
  - theme
tags:
  - vuepress
---
## five 
1
2
3
4
5
6
7
8

tagscategoriesblog插件配置中相对应。

  1. 编写.vue文件
// docs/.vuepress/theme/components/SubNav.vue
<template>
  <div class="subnav">
    <router-link to="/archives">文章总数:{{count}}</router-link>
    <router-link to="/categories">分类:{{$category.length}}</router-link>
    <router-link to="/tags">标签: {{$tag.length}}</router-link>
  </div>
</template>

<script>
export default {
  computed: {
    count() {
      let list = this.$site.pages.filter(item => {
        return item.id === 'post';
      })
      return list.length;
    }
  }
}
</script>

<style>

</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

$category$tag均为blog插件暴露到全局的计算属性,通过它俩我们很容易就得到了分类和标签的统计;文章总数则是通过默认的全局计算属性$site拿到全部的文档,然后再过滤id为post的文章进行计数。

运行结果如下:

截图

# 最后

Buy me a cup of coffee ☕.