vue2.x中使用cherry-markdown

发布时间 2023-05-30 11:00:05作者: Ning-

安装依赖

npm install cherry-markdown --save

子组件写法

​<template>
  <div @click.prevent.stop>
    <div
      :id="mdId"
      :style="{height:height+'px'}"
    />
  </div>
</template>

<script>
import Cherry from 'cherry-markdown'
import { getToken } from '@/utils/auth'
import 'cherry-markdown/dist/cherry-markdown.min.css'
export default {
  props: {
    height: {
      type: Number | String,
      default: 800
    },
    value: {
      type: String,
      default: ''
    },
    mdId: {
      type: String,
      default: 'markdown-container'
    }
  },
  data() {
    return {
      content: null,
      cherrInstance: null
    }
  },
  mounted() {
    this.initCherryMD()
  },
  methods: {
     // 初始化编辑器
    initCherryMD(value, config) {
      const { afterChange, afterInit, beforeImageMounted, fileUpload, mdId } = this
      const defaultValue = value || this.value
      this.cherrInstance = new Cherry({
        id: mdId,
        value: defaultValue,
        fileUpload: fileUpload,
        callback: {
          afterChange: afterChange,
          afterInit: afterInit,
          beforeImageMounted: beforeImageMounted
        }
      })
    },
    // 上传通用接口未实现audioVideo
    fileUpload(file) {
      const formData = new FormData()
      formData.append('smfile', file)
      const request = new XMLHttpRequest()
      // 图片上传路径修改为自己连接
      request.open('POST', process.env.PICTURE_API + '/file/ckeditorUploadFile?token=' + getToken())
      request.onload = this.onloadCallback
      request.send(formData)
    },
    onloadCallback(oEvent) {
      const currentTarget = oEvent.currentTarget
      console.log('返回的结果', currentTarget)
      if (currentTarget.status !== 200) {
        return this.$message({
          type: 'error',
          message: currentTarget.status + ' ' + currentTarget.statusText
        })
      }
      const resp = JSON.parse(currentTarget.response)
      let imgMdStr = ''
      if (resp.uploaded !== 1) {
        return this.$message({
          type: 'error',
          message: resp.error.message
        })
      }
      if (resp.uploaded === 1) {
        imgMdStr = `![${resp.fileName}](${resp.url})`
      }
      this.cherrInstance.insert(imgMdStr)
    },
    // 变更事件回调
    afterChange(e) {
      this.content = e
      const mdHtml = this.getCherryHtml()
      const mdTxt = e
      const mdContent = this.getCherryContent()
      this.$emit('input', mdHtml)
      this.$emit('md-change', mdHtml, mdTxt, mdContent)
    },
    // 初始化事件回调
    afterInit(e) {
      console.log(e)
    },
    // 图片加载回调
    beforeImageMounted(e, src) {
      console.log('bfImageMt', e, src)
      return { [e]: src }
    },
    setMarkdown(content, keepCursor) {
      if (!this.cherrInstance) { // 未加载则重新初始化
        this.initCherryMD(content)
        return
      }
      this.cherrInstance.setMarkdown(content)
    },
    getCherryContent() {
      const result = this.cherrInstance.getMarkdown()// 获取markdown内容
      return result
    },
    getCherryHtml() {
      const result = this.cherrInstance.getHtml()
      return result
    },
    getData() {
      const result = this.cherrInstance.getHtml()
      return result
    },
    /**
     * type:{'pdf'|'img'}
     */
    exportMD(type = 'pdf') {
      this.cherrInstance.export(type)
    },
    /**
     * model{'edit&preview'|'editOnly'|'previewOnly'}
     */
    switchModel(model) {
      if (this.isInit()) {
        this.cherrInstance.switchModel(model)
      }
    },

    insert(content, isSelect = false, anchor = [], focus = true) {
      this.cherrInstance.insert(content, isSelect, anchor, focus)
    },
    isInit() {
      if (this.cherrInstance) {
        return true
      }
      this.$message.warning('编辑器未初始化,请检查')
      return false
    }
  }
}
</script>

<style lang="scss" scoped>
</style>​

父组件使用

import CherryMD from '@/xxx/xxxx/xxx'

<CherryMD :height='800' v-model='form.mdContent'/>