vue 中使用 marked + highlight.js 代码高亮

markdown 代码高亮

需要依赖

  • npm install marked --save
  • npm install highlight.js --save

这里使用的主题是monokai-sublime.css可以自行更换主题。

结果

在这里插入图片描述

<template>
  <div>
    <div class="hljs" ref="hlDiv" v-html="code"></div>
  </div>
</template>

<script>
  import marked from 'marked'
  import hljs from "highlight.js";
  import javascript from 'highlight.js/lib/languages/javascript';
  import 'highlight.js/styles/monokai-sublime.css';

  export default {
    name: "height",
    data(){
      return {
        code:'```javascript\nfunction(){\n\tconsole.log(123)\n}\n```'
      }
    },
    mounted(){
      marked.setOptions({
          renderer: new marked.Renderer(),
          highlight: function(code) {
            return hljs.highlightAuto(code).value;
          },
          pedantic: false,
          gfm: true,
          tables: true,
          breaks: false,
          sanitize: false,
          smartLists: true,
          smartypants: false,
          xhtml: false
        }
      );
      this.code = marked(this.code)
    },
  }
</script>

猜你喜欢

转载自blog.csdn.net/Cribug8080/article/details/88748062