vue-markdown icon indicating copy to clipboard operation
vue-markdown copied to clipboard

很好用的markdown编辑器,我给大家贡献一份封装代码,让大家更方便使用

Open fengcms opened this issue 4 years ago • 1 comments

今天尝试了一下这个编辑器,很好用。希望作者可以不断维护。 随便它已经做得非常好,但是在和我们自己的项目中使用的时候,难免需要一些不必要的配置,因此我建议大家封装成一个自己的组件再使用。下面是我的封装代码:

<template>
  <div class="mark-editor">
    <div class="upload-progress" :style="`width:${progress}%`" />
    <MarkdownPro v-model="content" :toolbars="toolbars" theme="oneDark" @on-ready="ready" @on-upload-image="upImg" />
  </div>
</template>
<script>
import { MarkdownPro } from 'vue-meditor'
const editor = {}
export default {
  name: 'MarkEditor',
  components: { MarkdownPro },
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      content: '',
      toolbars: {
        uploadImage: true,
        split: true
      },
      progress: 0
    }
  },
  watch: {
    value (val) {
      this.content = val
    },
    content (val) {
      this.$emit('input', val)
    }
  },
  methods: {
    ready (el) {
      editor.vm = el.vm
      editor.insert = el.insertContent
    },
    upImg (file) {
      const formData = new FormData()
      formData.set('file', file)
      const xhr = new XMLHttpRequest()
      xhr.open('post', '/api/v1/upload')
      xhr.onload = () => {
        if (xhr.status === 200) {
          const res = JSON.parse(xhr.response || xhr.responseText)
          if (res.status === 0) {
            const imgMdStr = `\n![${file.name}](${res.data.path})\n`
            editor.insert(imgMdStr)
          } else {
            this.$message.error('图片上传失败')
          }
          this.progress = 0
        } else {
          this.$message.error('图片上传失败')
          this.progress = 0
        }
      }
      xhr.upload.onprogress = (e) => {
        // 上传进度
        if (e.lengthComputable) {
          this.progress = ~~(e.loaded / e.total * 100)
        }
      }
      xhr.send(formData)
    }
  }
}
</script>
<style lang="scss">
.mark-editor {
  position: relative;padding-top: 2px;
  .upload-progress {
    position: absolute;top: 0;left: 0;height: 2px;background: green;
  }
}
</style>

在需要使用的地方,直接调用这个组件即可,示例代码如下:

<MarkEditor v-model="form.markdown" />

其中图片上传部分,请根据自己的实际情况调整。

fengcms avatar May 06 '20 11:05 fengcms

自动生成文档目录 有没有思路

huakucha avatar Feb 24 '21 12:02 huakucha