Adding Tags to Vuepress

Tags: vuepress vuejs javascript

How to add a simple tag system to a Vuepress site.

First, add frontmatter to a markdown file with a list of tags. Example:

---
tags: ["vuepress", "vuejs"]
---

# Adding Tags to Vuepress
1
2
3
4
5

Write a Vue.js component to display the tags and place it in .vuepress/components so it becomes globally available:

<!-- .vuepress/components/TagLinks.vue -->
<template lang="html">
  <div>
    Tags:
    <router-link
      v-for="tag in $page.frontmatter.tags"
      :key="tag"
      :to="{ path: `/tags.html#${tag}`}">
      {{tag}}
    </router-link>
  </div>
</template>
1
2
3
4
5
6
7
8
9
10
11
12

Add the component to your markdown file (see line 7):







 

---
tags: ["vuepress", "vuejs"]
---

# Adding Tags to Vuepress

<TagLinks />
1
2
3
4
5
6
7

In .vuepress/components write a second Vue.js component called TagLinks.vue to display all the tags and pages across the site:

<!-- .vuepress/components/TagList.vue -->
<template lang="html">
  <div>
    <span v-for="tag in Object.keys(tags)">
      <h2 :id="tag">
        <router-link
          :to="{ path: `/tags.html#${tag}`}"
          class="header-anchor"
          aria-hidden="true">#</router-link>
        {{tag}}
      </h2>
      <ul>
        <li v-for="page in tags[tag]">
          <router-link
            :to="{ path: page.path}">{{page.title}}</router-link>
        </li>
      </ul>
    </span>
  </div>
</template>

<script>
export default {
  computed: {
    tags() {
      let tags = {}
      for (let page of this.$site.pages) {
        for (let index in page.frontmatter.tags) {
          const tag = page.frontmatter.tags[index]
          if (tag in tags) {
            tags[tag].push(page)
          } else {
            tags[tag] = [page]
          }
        }
      }
      return tags
    }
  }
}
</script>
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

Create tags.md, a simple markdown template in the root of your project:

# Tags

<TagList />
1
2
3

And that's it! If you want to see it in action, check out the two tags right under the title of this page.


Copyright © 2018 Daniel and Audrey Roy Greenfeld.
Site Map

Last Updated: 9/2/2018, 9:15:24 PM