7918 字
15 分钟

md-editor-v3 编辑器使用指南

文章摘要
DeepSeek R1
本文详细介绍了 md-editor-v3 编辑器的功能特性与使用技巧。编辑器支持 Markdown 编辑、语法快捷键、暗黑主题、图片上传与裁剪、内容格式化、全屏模式及预览功能。文章通过代码示例演示了 npm 安装与 script 标签引入两种使用方式,并讲解了内容渲染、标题导航实现、工具栏自定义、语言扩展和主题切换等高级功能,为开发者提供全面的集成与定制参考。

md-editor-v3 编辑器使用指南

本文将介绍 md-editor-v3 编辑器的使用方法和相关开发技巧。

该编辑器支持以下功能:

  • 基础的 Markdown 编辑
  • Markdown 语法快捷键
  • 内容自动保存
  • 暗黑主题
  • 图片上传/复制图片上传/裁剪图片上传
  • 内容格式化
  • 浏览器全屏/屏幕全屏模式
  • 仅预览模式

1. 基本使用

这里演示两种环境下的三种写法。

1.1 npm 安装用法

这种方式支持两种写法:.vue 模板写法和 jsx 语法。

安装

yarn add md-editor-v3

.vue 模板基础使用

import { defineComponent } from 'vue';
import MdEditor from 'md-editor-v3';
import 'md-editor-v3/lib/style.css';

export default defineComponent({
  components: { MdEditor },
  data() {
    return { text: '' };
  }
});

jsx 语法基础使用

import { defineComponent, ref } from 'vue';
import MdEditor from 'md-editor-v3';
import 'md-editor-v3/lib/style.css';

export default defineComponent({
  name: 'MdEditor',
  setup() {
    const text = ref('');
    return () => (
       (text.value = v)} />
    );
  }
});

1.2 script 标签引入用法

链接可前往 cdn.jsdelivr.net 搜索 md-editor-v3

注册组件

const App = {
  data() {
    return {
      text: 'Hello Editor!!'
    };
  }
};

Vue.createApp(App).use(MdEditorV3).mount('#md-editor-v3');

2. 渲染内容

该编辑器使用 marked 解析 Markdown 为 HTML,不支持扩展语法。

通常,编辑内容存储为 Markdown 格式,渲染时通过 marked 解析为 HTML。

2.1 默认渲染

1.3.0 版本后,编辑器支持 previewOnly 功能,可直接使用编辑器预览文章,不显示工具栏和编辑区域。

import { defineComponent } from 'vue';
import MdEditor from 'md-editor-v3';
import 'md-editor-v3/lib/style.css';

export default defineComponent({
  components: { MdEditor },
  data() {
    return { text: '## 我只会显示预览内容' };
  }
});

2.2 主动解析演示

这种方式用于保存 Markdown 内容,然后自行解析。

import marked from 'marked';

// 代码高亮
import hljs from 'highlight.js';
// 自选代码高亮样式
import 'highlight.js/scss/atom-one-dark.scss';

// 用于记录标题数,根据业务调整
let count = 0;
// 记录标题内容
const headsTemp = [];

// marked 设置
const rendererMD = new marked.Renderer();

// 调整标题内容
rendererMD.heading = (text, level) => {
  headsTemp.push({ text, level });
  count++;
  return `${text}`;
};

// 设置图片内容,统一显示一张缓存图,用于懒加载
rendererMD.image = (href, _, text) =>
  ``;

marked.setOptions({
  highlight(code) {
    return hljs.highlightAuto(code).value;
  },
  renderer: rendererMD
});

// 这里的 html 就是插入到页面的元素文本了
const html = marked('## Markdown 内容');

2.3 标题导航实现

上面的例子中,headsTemp 记录了解析过程中的所有标题,可用于构建标题导航。

下面演示基于 ant-design-vue 的版本。代码使用 jsx 语法,.vue 模板语法请自行调整。

Recursive.tsx - 导航中的链接组件

import { Anchor } from 'ant-design-vue';
import { defineComponent, PropType } from 'vue';

const { Link } = Anchor;

export interface Head {
  text: string;
  level: number;
}

export interface TocItem extends Head {
  anchor: string;
  children?: Array;
}

const Recursive = defineComponent({
  props: {
    tocItem: {
      type: Object as PropType,
      default: () => ({})
    }
  },
  setup({ tocItem }) {
    return () => (
      
        {tocItem.children &&
          tocItem.children.map((item) => )}
      
    );
  }
});

export default Recursive;

Topicfy.tsx - 用于生成整个导航内容

import { Anchor } from 'ant-design-vue';
import { computed, defineComponent, PropType, ref, watch } from 'vue';

import Recursive, { Head, TocItem } from './Recursive';

const Topicfy = defineComponent({
  props: {
    // 解析得到的标题列表
    heads: {
      type: Array as PropType,
      required: true
    }
  },
  setup(props) {
    const topics = computed(() => {
      const tocItems: TocItem[] = [];
      let count = 0;

      const add = (text: string, level: number) => {
        count++;
        const item = { anchor: `heading-${count}`, level, text };

        if (tocItems.length === 0) {
          tocItems.push(item);
        } else {
          let lastItem = tocItems[tocItems.length - 1];

          if (item.level > lastItem.level) {
            for (let i = lastItem.level + 1; i  add(h.text, h.level));
      return tocItems;
    });

    return () => (
      
        {topics.value.map((item) => (
          
        ))}
      
    );
  }
});

export default Topicfy;

该组件参考了网络上的实现,非完全原创。React 版本参考 Topicfy

2.4 获取 HTML 代码

编辑器提供了 onHtmlChanged 方法,用于在编辑内容变化后获取 marked 编译的 HTML 内容。

import { defineComponent } from 'vue';
import MdEditor from 'md-editor-v3';
import 'md-editor-v3/lib/style.css';

export default defineComponent({
  components: { MdEditor },
  data() {
    return { text: '' };
  },
  methods: {
    saveHtml(h) {
      console.log(h);
    }
  }
});

jsx 语法用法相同。

3. 编辑器的功能演示

3.1 扩展库链接

编辑器扩展内容大多使用 CDN,同时支持内网链接扩展。

import { defineComponent } from 'vue';
import MdEditor from 'md-editor-v3';
import 'md-editor-v3/lib/style.css';

export default defineComponent({
  components: { MdEditor },
  data() {
    return {
      text: '',
      editorConfig: {
        markedUrl: '/marked.min.js',
        highlightUrl: '/highlight.min.js',
        prettierUrl: {}
      }
    };
  }
});

v1.2.0 版本目前支持上述链接,图标链接将在后续版本中添加。

3.2 工具栏自定义

默认显示全部工具栏,每个功能都绑定了快捷键。可通过 toolbarstoolbarsExclude API 自定义显示。toolbarsExclude 优先级更高。

示例:不显示 GitHub 按钮

import { defineComponent } from 'vue';
import MdEditor from 'md-editor-v3';
import 'md-editor-v3/lib/style.css';

export default defineComponent({
  components: { MdEditor },
  data() {
    return {
      text: '',
      toolbars: [
        'bold',
        'underline',
        'italic',
        'strikeThrough',
        'sub',
        'sup',
        'quote',
        'unorderedList',
        'orderedList',
        'codeRow',
        'code',
        'link',
        'image',
        'table',
        'revoke',
        'next',
        'save',
        'pageFullscreen',
        'fullscreen',
        'preview',
        'htmlPreview'
      ],
      toolbarsExclude: ['github']
    };
  }
});

3.3 扩展语言

编辑器默认内置中文和英文,两者均可通过扩展 API 覆盖。主要用于设置内容提示,如弹窗标题等。

扩展一门语言,取名为 zh-NB

import { defineComponent } from 'vue';
import MdEditor, { StaticTextDefaultValue } from 'md-editor-v3';
import 'md-editor-v3/lib/style.css';

const languageUserDefined: { 'zh-NB': StaticTextDefaultValue } = {
  'zh-NB': {
    toolbarTips: {
      bold: '加粗',
      underline: '下划线',
      italic: '斜体',
      strikeThrough: '删除线',
      title: '标题',
      sub: '下标',
      sup: '上标',
      quote: '引用',
      unorderedList: '无序列表',
      orderedList: '有序列表',
      codeRow: '行内代码',
      code: '块级代码',
      link: '链接',
      image: '图片',
      table: '表格',
      revoke: '后退',
      next: '前进',
      save: '保存',
      prettier: '美化',
      pageFullscreen: '浏览器全屏',
      fullscreen: '屏幕全屏',
      preview: '预览',
      htmlPreview: 'html代码预览',
      github: '源码地址'
    },
    titleItem: {
      h1: '一级标题',
      h2: '二级标题',
      h3: '三级标题',
      h4: '四级标题',
      h5: '五级标题',
      h6: '六级标题'
    },
    linkModalTips: {
      title: '添加',
      descLable: '链接描述:',
      descLablePlaceHolder: '请输入描述...',
      urlLable: '链接地址:',
      UrlLablePlaceHolder: '请输入链接...',
      buttonOK: '确定',
      buttonUpload: '上传'
    },
    // v1.2.0 新增
    clipModalTips: {
      title: '裁剪图片上传',
      buttonUpload: '上传'
    },
    // v1.1.4 新增
    copyCode: {
      text: '复制代码',
      tips: '已复制'
    }
  }
};

export default defineComponent({
  components: { MdEditor },
  data() {
    return {
      text: '',
      language: 'zh-NB',
      languageUserDefined
    };
  }
});

如果 key = 'zh-CN',即可覆盖默认中文,其他语言同理。

3.4 主题切换

编辑器内置暗黑主题默认主题,通过 theme API 切换。

import { defineComponent } from 'vue';
import MdEditor from 'md-editor-v3';
import 'md-editor-v3/lib/style.css';

export default defineComponent({
  components: { MdEditor },
  data() {
    return {
      text: '',
      theme: 'dark'
    };
  }
});

4. 结尾

更多更新请关注:md-editor-v3


✨ 感谢您的耐心阅读!
✨ 文章仅限学习使用~
✨ 文章转载于网络,如有侵权,请联系删除。

Firefly
Firefly
Hello, I'm Firefly.
公告
欢迎体验 Firefly 主题复刻版,壁纸与布局已全面同步。
查看文档