vue中使用Markdown样式

1,217 阅读1分钟

引入github的Markdown样式

github.com/sindresorhu…

安装:

yarn add github-markdown-css

使用:

1、引入import'github-markdown-css'

2、需要在最外层的元素上加上class='markdown-body'

列子:getStart.vue

getStart.vue

<template>
  <article class="markdown-body">
    <h1>开始使用</h1>
    <p>请先<a href="#/doc/install">安装</a>本组件库。</p>
    <p>然后在你的代码中写入下面的代码</p>
    <pre><code>import {Button, Tabs, Switch, Dialog} from "ui"</code></pre>
    就可以使用我提供的组件了。
    <h2>Vue 单文件组件</h2>
  </article>
</template>

支持导入md文件(vue3 vite plugin)

由于我用的vite,需要自制vite插件

安装

安装 marked 【yarn add --dev marked】

自制vite插件 将md结尾的转换为js

plugins/md.ts

import * as path from 'path'
import * as fs from 'fs';
// import marked from 'marked';
const { marked } = require('marked');

const mdToJs = str => {
    const content = JSON.stringify(marked(str))
    return `export default ${content}`
}

export function md() {
    return {
        configureServer: [ // 用于开发
            async ({ app }) => {
                app.use(async (ctx, next) => { // koa
                    if (ctx.path.endsWith('.md')) {
                        ctx.type = 'js'
                        const filePath = path.join(process.cwd(), ctx.path)
                        ctx.body = mdToJs(fs.readFileSync(filePath).toString())
                    } else {
                        await next()
                    }
                })
            },
        ],
        transforms: [{  // 用于 rollup // 插件
            test: context => context.path.endsWith('.md'),
            transform: ({ code }) => mdToJs(code)
        }]
    }
}
添加vite.config.ts
// @ts-nocheck
import { md } from "./plugins/md";

export default {
    plugins: [md()]
};

写一个md文件(get-started.md),然后引入就可以了

<template>
  <article class="markdown-body" v-html="md"></article>
</template>
<script lang="ts">
import md from '../get-started.md'
export default {
  setup() {
    return { md };
  },
};
</script>

当多个页面都用这个模板的时候,我们就需要动态加载导入模块,代码如下:异步导入,当导入成功之后再将值赋给变量

<template>
  <article class="markdown-body" v-html="md"></article>
</template>
<script lang="ts">
import { ref } from "vue";
export default {
  props: {
    path: {
      type: String,
      required: true,
    },
  },
  setup(props) {
    const md = ref(null);
    import(props.path).then((result) => {
      md.value = result.default;
    });
    return { md };
  },
};
</script>