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.效果
|