vue实现markdown
Vue 实现 Markdown 编辑器
在 Vue 中实现 Markdown 编辑器可以通过集成现有的库或自行构建。以下是几种常见的方法:
使用 marked 和 highlight.js
安装依赖:
npm install marked highlight.js
在 Vue 组件中引入并使用:
<template>
<div>
<textarea v-model="markdown" @input="updatePreview"></textarea>
<div v-html="compiledMarkdown"></div>
</div>
</template>
<script>
import marked from 'marked';
import hljs from 'highlight.js';
import 'highlight.js/styles/github.css';
marked.setOptions({
highlight: function(code, lang) {
if (lang && hljs.getLanguage(lang)) {
return hljs.highlight(lang, code).value;
}
return hljs.highlightAuto(code).value;
}
});
export default {
data() {
return {
markdown: '# Hello Markdown',
compiledMarkdown: ''
}
},
mounted() {
this.updatePreview();
},
methods: {
updatePreview() {
this.compiledMarkdown = marked(this.markdown);
}
}
}
</script>
使用 vue-markdown 组件
安装依赖:
npm install vue-markdown
在组件中使用:
<template>
<div>
<textarea v-model="markdown"></textarea>
<vue-markdown :source="markdown"></vue-markdown>
</div>
</template>
<script>
import VueMarkdown from 'vue-markdown';
export default {
components: {
VueMarkdown
},
data() {
return {
markdown: '# Hello Vue Markdown'
}
}
}
</script>
使用 Vditor(功能丰富的 Markdown 编辑器)
安装依赖:
npm install vditor
在 Vue 中使用:
<template>
<div id="vditor"></div>
</template>
<script>
import Vditor from 'vditor';
import 'vditor/dist/index.css';
export default {
mounted() {
this.vditor = new Vditor('vditor', {
height: 500,
after: () => {
this.vditor.setValue('# Hello Vditor');
}
});
},
beforeDestroy() {
if (this.vditor) {
this.vditor.destroy();
}
}
}
</script>
自定义 Markdown 解析器
如果需要更轻量级的解决方案,可以自行实现基本 Markdown 解析:
<template>
<div>
<textarea v-model="markdown" @input="parseMarkdown"></textarea>
<div v-html="htmlOutput"></div>
</div>
</template>
<script>
export default {
data() {
return {
markdown: '# Hello',
htmlOutput: ''
}
},
methods: {
parseMarkdown() {
this.htmlOutput = this.markdown
.replace(/^# (.*$)/gm, '<h1>$1</h1>')
.replace(/^## (.*$)/gm, '<h2>$1</h2>')
.replace(/^### (.*$)/gm, '<h3>$1</h3>')
.replace(/\*\*(.*)\*\*/g, '<strong>$1</strong>')
.replace(/\*(.*)\*/g, '<em>$1</em>')
.replace(/\n/g, '<br>');
}
},
mounted() {
this.parseMarkdown();
}
}
</script>
集成 Monaco Editor 实现高级编辑
对于需要类似 VSCode 体验的 Markdown 编辑器:
npm install monaco-editor
Vue 组件实现:
<template>
<div id="editor-container" style="height: 500px"></div>
</template>
<script>
import * as monaco from 'monaco-editor';
export default {
mounted() {
this.editor = monaco.editor.create(document.getElementById('editor-container'), {
value: '# Markdown Editor',
language: 'markdown',
theme: 'vs-dark',
minimap: { enabled: true }
});
},
beforeDestroy() {
this.editor.dispose();
}
}
</script>
功能比较
- marked + highlight.js:轻量级,适合简单需求
- vue-markdown:Vue 专用,中等功能
- Vditor:功能全面,包含预览、工具栏等
- Monaco Editor:专业级编辑体验,适合复杂场景
- 自定义解析器:完全控制,但功能有限
根据项目需求选择合适的方案,大多数情况下使用现成库更高效可靠。







