vue2实现markdown编辑器,实现同步滚动,实时预览等功能

「本文已参与好文召集令活动,点击查看:后端、大前端双赛道投稿,2万元奖池等你挑战!」

效果图

image.png

依赖:v-md-editor

中文文档:v-md-editor

本文使用的是进阶版

1. 先安装v-md-editor

# use npm
npm i @kangc/v-md-editor -S

# use yarn
yarn add @kangc/v-md-editor
复制代码

2. Quick Start

import Vue from 'vue';
import VueMarkdownEditor from '@kangc/v-md-editor';
import '@kangc/v-md-editor/lib/style/base-editor.css';
import vuepressTheme from '@kangc/v-md-editor/lib/theme/vuepress.js';

VueMarkdownEditor.use(vuepressTheme);

Vue.use(VueMarkdownEditor);
复制代码

3. 使用

<template>
  <v-md-editor v-model="text" height="400px"></v-md-editor>
</template>

<script>
export default {
  data() {
    return {
      text: '',
    };
  },
};
</script>
复制代码

4. 引入vuepress 主题

扩展 markdown-it

import Prism from 'prismjs';

VueMarkdownEditor.use(vuepressTheme, {
  Prism,
  extend(md) {
    // md为 markdown-it 实例,可以在此处进行修改配置,并使用 plugin 进行语法扩展
    // md.set(option).use(plugin);
  },
});
复制代码

扩展代码高亮语言包

请通过babel-plugin-prismjs (opens new window)插件按需引入对应的语言包。

安装 babel-plugin-prismjs 插件

# yarn
yarn add babel-plugin-prismjs --dev

# npm
npm install babel-plugin-prismjs
复制代码

按需引入语言包(推荐)

// babel.config.js
module.exports = {
  plugins: [
    [
      'prismjs',
      {
        languages: ['json'],
      },
    ],
  ],
};
复制代码

5. 加上图片上传功能(上传本地图片)

原理:上传图片至文件服务器,上传成功后将返回的图片相关信息插入编辑区域。

image.png

注意

上传图片菜单默认为禁用状态 设置disabled-menus 为空数组可以开启。`

示例代码
<template>
  <v-md-editor
    v-model="text"
    left-toolbar="undo redo | image"
    :disabled-menus="[]"
    @upload-image="handleUploadImage"
    height="500px"
  />
</template>

<script>
export default {
  data() {
    return {
      text: '',
    };
  },
  methods: {
    handleUploadImage(event, insertImage, files) {
      // 拿到 files 之后上传到文件服务器,然后向编辑框中插入对应的内容
      console.log(files);

      // 此处只做示例
      insertImage({
        url:
          'https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=1269952892,3525182336&fm=26&gp=0.jpg',
        desc: '七龙珠',
        // width: 'auto',
        // height: 'auto',
      });
    },
  },
};
</script>
复制代码

最后总结:

代码汇总并讲解

<template>
    <vue-markdown-editor
      v-model="editor"
      height="100%"
      :disabled-menus="[]"
      @upload-image="onUploadImage"
      ></vue-markdown-editor>
  </template>
  
  <script>
import VueMarkdownEditor from '@kangc/v-md-editor'
import '@kangc/v-md-editor/lib/style/base-editor.css'
import vuepressTheme from '@kangc/v-md-editor/lib/theme/vuepress.js'
import '@kangc/v-md-editor/lib/theme/style/vuepress.css'

import Prism from 'prismjs'
import axios from 'axios'
import auth from '@/utils/auth'
VueMarkdownEditor.use(vuepressTheme, { Prism, extend(md) {} })
  export default {
    data() {
      return {
        editor: '',
      }
    },
    components: { VueMarkdownEditor },
    mounted() {
        document.querySelector('.v-md-editor').style.height = document.body.offsetHeight - 50 + 'px'
    },
    methods: {
         // 上传图片
        onUploadImage(event, insertImage, files) {
            const file = files[0],
                  path = process.env.VUE_APP_BASE_API,
                  index = path.lastIndexOf("\/")
            let param = new FormData()
            param.append('image', file)
            const config = { headers: {
              'Content-Type': 'multipart/form-data',
              'Authorization': auth.getToken()
            } }
            axios.post(`${path}doc/uploadfile/`, param, config).then(r => {
                if(r.data.code == 200) {
                  const last = path.slice(0, index)
                  insertImage({
                      url: last + r.data.data.url,
                      desc: files[0].name
                  })
                }
            }).catch(e => {
                this.Toast(2, '图片上传出了点小问题,请稍后重试')
            })
        }
    }
  };
  </script>
  <style>
.vuepress-markdown-body h1{ font-size: 28px; }
.vuepress-markdown-body h2{ font-size: 26px; }
.vuepress-markdown-body h3{ font-size: 24px; }
.vuepress-markdown-body h4{ font-size: 22px; }
.vuepress-markdown-body h5{ font-size: 20px; }
.vuepress-markdown-body:not(.custom){padding: 5px 10px!important;}
  </style>
复制代码
  1. document.querySelector('.v-md-editor').style.height = document.body.offsetHeight - 50 + 'px' 这步是为了markdown编辑器可以跟body元素高度一致,确保铺满屏幕

  2. style的字体设置,是因为我有base样式库,h标签的大小等,已处理过,所以这里要重新处理一下

  3. onUploadImage这是图片上传的方法

结尾

人懒,不想配图,望能帮到大家

公众号:小何成长,佛系更文,都是自己曾经踩过的坑或者是学到的东西

有兴趣的小伙伴欢迎关注我哦,我是:何小玍。 大家一起进步鸭

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享