当前位置:首页 > VUE

vue实现md编辑展示

2026-02-23 13:34:11VUE

Vue 实现 Markdown 编辑与展示

安装依赖

需要安装 markdown-itmarked 进行 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 实现分栏编辑与实时预览:

vue实现md编辑展示

.container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}
textarea {
  min-height: 300px;
  width: 100%;
}

标签: 编辑vue
分享给朋友:

相关文章

vue实现展开与收起

vue实现展开与收起

Vue 实现展开与收起功能 在 Vue 中实现展开与收起功能可以通过多种方式完成,以下是一些常见的方法: 使用 v-show 或 v-if 控制显示 通过 Vue 的指令 v-show 或 v-if…

vue实现https

vue实现https

Vue 中实现 HTTPS 的步骤 在 Vue 项目中实现 HTTPS 主要涉及开发环境配置和生产环境部署。以下是具体方法: 开发环境配置(Vue CLI 或 Vite) 使用 mkcert 生成…

vue实现treeview

vue实现treeview

Vue 实现 TreeView 的方法 使用递归组件实现 TreeView 递归组件是 Vue 中实现 TreeView 的常见方式。通过组件调用自身,可以轻松处理嵌套的树形结构数据。 <te…

vue nexttrick实现

vue nexttrick实现

Vue 中 nextTick 的实现原理 nextTick 是 Vue 提供的一个异步方法,用于在下次 DOM 更新循环结束之后执行延迟回调。它利用了 JavaScript 的事件循环机制,确保回调在…

vue实现爬虫

vue实现爬虫

Vue 实现爬虫的基本思路 Vue.js 本身是一个前端框架,主要用于构建用户界面。要实现爬虫功能,通常需要结合后端技术或浏览器自动化工具。以下是几种常见的方法: 方法一:Vue + Node.js…

vue实现标注

vue实现标注

Vue 实现标注功能的方法 使用 Vue 实现标注功能可以通过多种方式实现,以下介绍几种常见的方法: 1. 使用 HTML5 Canvas 实现标注 Canvas 提供了强大的绘图能力,适合实现复…