MarkdownのHTMLレンダリングをNuxt.jsのアプリに実装してみる

Nuxt.jsのアプリにMarkdownを表示させてみます。MarkdownからHTMLへの変換です。Nuxt 2です。

パッケージインストール

$ npm install @nuxtjs/markdownit

package.json の依存性の記述には以下が追加されました。

    "@nuxtjs/markdownit": "^2.0.0",

nuxt.config.js に以下のような記述を追加します。

  modules: [
    '@nuxtjs/markdownit',
  ],

  markdownit: {
    // ref: https://github.com/markdown-it/markdown-it
    linkify: true,
    breaks: true,
    use: [
    ],
  },

Vueファイル記述

HTMLの部分の記述例です。 $md.render というメソッドを呼び出して v-html に指定します。

<v-card-text>
  <div class="markdown" v-html="$md.render(content)"></div>
</v-card-text>

content にはMarkdownサンプルを以下のように文字列で直書きしておきます。Markdown書式でタイトル、コード、箇条書き、テーブル表示をサンプルに含めています。

export default {
  data() {
    return {
      content: `
# title 1

## title 2

### title 3

\`\`\`cpp
#include <iostream>

int main() {
    std::cout << "Hello, World!" << std::endl;
    return 0;
}
\`\`\`

C++プログラムは、\`main()\` 関数から実行を開始します。

- 東京都
- 神奈川県
- 千葉県
- 埼玉県

| 都道府県 | 県庁所在地 |
|---------|---------|
| 東京都   | 東京      |
| 神奈川県 | 横浜      |
| 埼玉県   | 埼玉      |
| 千葉県   | 千葉      |
| 茨城県   | 水戸      |
| 栃木県   | 宇都宮    |
| 群馬県   | 前橋      |
`
    }
  }
}

以下のようになりました。MarkdownがHTMLに変換され、表示されています。

※このMarkdownテキストのサンプルは、ChatGPTにいくつか質問した断片を集めたものです。最後は県庁所在地を聞いたものですが、埼玉県の県庁所在地が誤っていて、「さいたま」が正解です。

見た目を整える

CSSを以下のように書きます。内容はお好みに応じてです。

.markdown h1,
.markdown h2,
.markdown h3,
.markdown p,
.markdown pre,
.markdown ul,
.markdown table {
  margin-top: 10px;
  margin-bottom: 10px;
}

.markdown table {
  border-collapse: separate;
  border-spacing: 0 0;
}

.markdown table th,
.markdown table td {
  padding: 6px 12px;
  border-bottom: 1px solid #eeeeee;
  border-right: 1px solid #eeeeee;
}

.markdown table tr:first-child th {
  border-top: 1px solid #eeeeee;
  background-color: #333;
}

.markdown table tr th:first-child,
.markdown table tr td:first-child {
  border-left: 1px solid #eeeeee;
}

.markdown table tr:first-child th:first-child {
  border-top-left-radius: 8px;
}

.markdown table tr:first-child th:last-child {
  border-top-right-radius: 8px;
}

.markdown table tr:last-child td:first-child {
  border-bottom-left-radius: 8px;
}

.markdown table tr:last-child td:last-child {
  border-bottom-right-radius: 8px;
}

table関連の指定はChatGPTのテーブル表示に寄せました。

テーブルの枠線で色を指定している箇所があります。ダークモード前提での配色ですので、適宜調整してください。

コード表示のところ(<pre>...</pre>)を整えたいのですが、次の記事に書くことにします。

追記

次の記事 qiita.com