vue + vditor(markdown编辑器)

Vditor 是一款浏览器端的 Markdown 编辑器,支持所见即所得、即时渲染(类似 Typora)和分屏预览模式。它使用 TypeScript 实现,支持原生 JavaScript 以及 Vue、React、Angular 和 Svelte 等框架。

1.vue2 安装(建议安装3.7.7及以下版本)

npm install [email protected]

 2.vditor组件

<template>
  <div id="vditor" />
</template>
<script>
import Vditor from "vditor"
import "vditor/dist/index.css"

export default {
  props: {
    value: {
      type: String,
      default: ''
    },
    id: {
      type: String,
      required: false,
      default () {
        return 'markdown-editor-' + +new Date() + ((Math.random() * 1000).toFixed(0) + '')
      }
    },
    isHideTools: {
      type: Boolean,
      required: false,
      default: false
    },
    isPin: {
      type: Boolean,
      required: false,
      default: true
    },
    height: {
      type: String,
      required: false,
      default: '300px'
    },
    width: {
      type: String,
      required: false,
      default: "auto"
    },
    mode: {
      type: String,
      required: false,
      default: 'sv'
    },
  },
 
  data () {
    return {
      vditor: ""
    }
  },
  //mounted
  mounted () {
    this.vditor = new Vditor("vditor", {
      height: this.height,
      width: this.width,
      toolbarConfig: {
        pin: this.isPin,
        hide: this.isHideTools,
      },
      cache: {
        enable: false
      },
      toolbar: [
        "emoji",
        "headings",
        "bold",
        "italic",
        "strike",
        "link",
        "|",
        "list",
        "ordered-list",
        "check",
        "outdent",
        "indent",
        "|",
        "quote",
        "line",
        "code",
        "inline-code",
        "insert-before",
        "insert-after",
        "|",
        //"upload",
        // "record",
        { //自定义上传
          hotkey: "",
          name: "upload",
          // tipPosition: "s",
          tip: "上传图片",
          className: "right",
        },
 
        "table",
        "|",
        "undo",
        "redo",
        "|",
        // "fullscreen",
        "edit-mode",
        {
          name: "more",
          toolbar: [
            //"both",
            "code-theme",
            "content-theme",
            "export",
            "outline",
            "preview",
            //"devtools",
            // "info",
            //"help",
          ],
        },
      ],
      after: () => {
        this.vditor.setValue(this.value)
      },
      mode: this.mode,
      preview: {
        mode: "both",
        actions: []
      },
      upload: {
        accept: 'image/*',// 规定上传的图片格式
        url: "/api/uploadFile",// 请求的接口
        multiple: false,
        fieldName: 'file',
        max: 10 * 1024 * 1024,//上传图片的大小
        // extraData: { 'access_token': this.token }, // 为 FormData 添加额外的参数
        linkToImgUrl: "/api/admin/uploadFile",
        validate (files) {
          const isLessthan10M = files[0].size / 1024 / 1024 < 10
          if (!isLessthan10M) {
            //this.$message.error('上传图片大小不能超过 10MB!')
          }
        },
        // 上传图片回显处理
        format (files, responseText) {
          var self = this;
          var data = JSON.parse(responseText)
          // 上传图片请求状态
          if (data.status) {
            let filName = data.msg
            let lastTipNum = filName.substr(filName.lastIndexOf('/', filName.lastIndexOf('/') - 1) + 1);
            let index = lastTipNum.lastIndexOf("\/");
            let succ = {}
            succ[filName] = "/api" + data.data
            //图片回显
            return JSON.stringify({
              data,
              data,
              data: {
                errFiles: [],
                succMap: succ
              }
            })
          } else {
            Message({
              message: "图片上传失败",
              type: 'error',
            })
          }
 
        },
        error (msg) {
          console.log(msg + "上传失败")
        },
      }
    })
    this.unwatch = this.$watch('value', (val) => {
       if (this.vditor  && this.getValue() !== val) {
            this.setValue(val)  
       }
    )
  },
  beforeDestory() {
    if (this.unwatch) {
        this.unwatch()
    }
    if (this.vditor) {
        this.vditor.destory()
    }
  },
  methods: {
    getValue () {
      return this.vditor.getValue();
    },
    getHTML () {
      return this.vditor.getHTML();
    },
    setValue (value) {
      return this.vditor.setValue(value);
    },
    disabled () {
      return this.vditor.disabled();
    },
  },
 
}
</script>

注:

        1.在mounted 中等vditor 初始化完成后,再通过监听value设置编辑器的值

        2. beforeDestory() 销毁操作

3. vue3安装最新版本即可

pnpm i vditor@next -S

4.更多配置参考vditor官网

猜你喜欢

转载自blog.csdn.net/qq_44376306/article/details/130607292