Vue中使用marked

marked官方文档
官方demo地址

1. 安装依赖

yarn add marked highlight.js -S, 其中 highlight.js用来高亮代码块

2. 使用(语法是V3 setup+ TS )

import 'highlight.js/styles/monokai-sublime.css' 是用来设置代码块的样式

<template>
  <div class="markdown-box">
    <!-- 书写区域 -->
    <textarea class="markdown-box-write" @input="writeChange"></textarea>
    <!-- 编译区域 -->
    <div class="markdown-box-compile" v-html="compileHtml"></div>
  </div>
</template>
import { marked } from 'marked'
import { shallowRef } from 'vue'
import 'highlight.js/styles/monokai-sublime.css'
marked.setOptions({
  renderer: new marked.Renderer(),
  highlight: function (code, lang) {
    const hljs = require('highlight.js')
    const language = hljs.getLanguage(lang) ? lang : 'plaintext'
    return hljs.highlight(code, { language }).value
  },
  langPrefix: 'hljs language-',
  breaks: false,
  gfm: true,
  headerIds: true,
  headerPrefix: '',
  mangle: true,
  pedantic: false,
  sanitize: false,
  silent: false,
  smartLists: false,
  smartypants: false,
  xhtml: false
})
const compileHtml = shallowRef()

/** 输入框改变事件 */
const writeChange = (e: Event) => {
  const getTextArea = e.target as HTMLTextAreaElement
  compileHtml.value = marked.parse(getTextArea.value)
}

3.效果

在这里插入图片描述

Logo

前往低代码交流专区

更多推荐