vue实现md编辑展示
Vue 实现 Markdown 编辑与展示
安装依赖
需要安装 markdown-it 或 marked 进行 Markdown 解析,以及 highlight.js 实现代码高亮。通过以下命令安装:
npm install markdown-it highlight.js
创建 Markdown 编辑器组件
使用 textarea 或第三方库(如 @toast-ui/editor)作为编辑区域,实时绑定数据:
<template>
<div>
<textarea v-model="markdownText" placeholder="输入Markdown内容"></textarea>
<div v-html="compiledMarkdown" class="preview"></div>
</div>
</template>
<script>
import markdownIt from 'markdown-it';
import hljs from 'highlight.js';
export default {
data() {
return {
markdownText: '',
md: markdownIt({
highlight: (code, lang) => {
if (lang && hljs.getLanguage(lang)) {
return hljs.highlight(lang, code).value;
}
return hljs.highlightAuto(code).value;
}
})
};
},
computed: {
compiledMarkdown() {
return this.md.render(this.markdownText);
}
}
};
</script>
<style>
/* 引入highlight.js主题 */
@import 'highlight.js/styles/github.css';
.preview {
border: 1px solid #eee;
padding: 10px;
}
</style>
使用第三方编辑器库
若需要更完整的编辑功能(如工具栏),可集成 @toast-ui/vue-editor:

npm install @toast-ui/editor @toast-ui/vue-editor
组件示例:
<template>
<Editor
initialValue="初始内容"
:options="{ hideModeSwitch: true }"
@change="onChange"
/>
</template>
<script>
import { Editor } from '@toast-ui/vue-editor';
import '@toast-ui/editor/dist/toastui-editor.css';
export default {
components: { Editor },
methods: {
onChange(content) {
console.log(content);
}
}
};
</script>
安全注意事项
使用 v-html 渲染时需防范 XSS 攻击。可通过以下方式增强安全性:

- 使用
DOMPurify清理 HTML:npm install dompurify - 在计算属性中处理:
import DOMPurify from 'dompurify'; // ... compiledMarkdown() { return DOMPurify.sanitize(this.md.render(this.markdownText)); }
自定义 Markdown 解析
通过 markdown-it 插件扩展功能,例如添加表格支持:
import markdownIt from 'markdown-it';
import markdownItTable from 'markdown-it-multimd-table';
const md = markdownIt().use(markdownItTable);
响应式预览
结合 CSS 实现分栏编辑与实时预览:
.container {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 20px;
}
textarea {
min-height: 300px;
width: 100%;
}






