Vue项目渲染markdown文件

5,880 阅读1分钟

需要安装的依赖及用法

  1. vue-markdown
    在需要的页面引入
<template>
  <div class="markdown-body">
    <VueMarkdown :source="mdData" v-highlight></VueMarkdown>
  </div>
</template>

import VueMarkdown from 'vue-markdown';
// 这种方式引入 数据可直接使用
import markdownData from './xxx.md';
export default {
  components: {
    VueMarkdown
  },
  data() {
    return {
      mdData: markdownData
    }
  },
}
  1. github-markdown-css
    在main.js中引入
    import 'github-markdown-css/github-markdown.css'
    在使用VueMarkdown的外层div标签上添加类名 markdown-body
<div class="markdown-body">
  <VueMarkdown :source="mdData" v-highlight></VueMarkdown>
</div>
  1. highlight.js
    自定义指令 v-highlight
import hljs from 'highlight.js'
// 如果开启了typescript 需要额外安装 npm install @types/highlight.js
// 通过 import * as hljs from 'highlight.js' 引入
Vue.directive('highlight', function (el) {
  const blocks = el.querySelectorAll('pre code')
  blocks.forEach(block => {
    hljs.highlightBlock(block)
  })
})
  1. text-loader 解析.md文件的loader vue.config.js
module.exports = {
  configureWebpack: {
    module: {
      rules: [
        {
          test: /\.md$/,
          use: 'text-loader'
        }
      ]
    }
  }
}

参考