Requirements describe

Mavon-editor adds file upload functionality and inserts the file address at the current cursor position.

Implementation approach

  1. Add a custom icon on the toolbar
  2. Listen for custom button events
  3. After the file is uploaded, insert the file name and file address in the position where the cursor is located

Toolbar Custom ICONS

The editor actually has four slots, respectively in front of the left toolbar, left toolbar behind, right toolbar in front of the right toolbar, right toolbar behind

    <mavon-editor
      ref="md"
      v-model="newValue"
    >
      <! Insert our icon into the toolbar via slot --> insert our icon into the toolbar via slot -->
      <! -- left-toolbar-before -->
      <! -- left-toolbar-after -->
      <! -- right-toolbar-before -->
      <! -- right-toolbar-after -->
      <template v-slot:left-toolbar-after>
        <button
          type="button"
          title="File upload"
          class="op-icon fa markdown-upload iconfont iconupload"
          aria-hidden="true"
          @click="uploadFile"
        >
          <! The element UI icon is used here.
          <i class="el-icon-upload" />
        </button>
      </template>
    </mavon-editor>
    
    <! Put a hidden input here to select the file -->
    <input ref="uploadInput" style="display: none" type="file" @change="uploadFileChange">
Copy the code
Results the following

Click to trigger the select file and upload function

    // This is our custom button trigger method, but we can also do some other things while we customize other functions.
    uploadFile() {
      // Find the hidden input tag by ref and trigger its click method
      this.$refs.uploadInput.click()
    },
    // Listen on input to get the status of the file
    uploadFileChange(e) {
      // Get the file selected by input
      const file = e.target.files[0]
      // Create the data in the form format, place the file in the form, logo is the field defined in the background
      const formdata = new FormData()
      formdata.append('logo', file)

      // Send the request, here is each axios request, the method is changed according to their project
      axios.post('/upload',formdata).then(res= > {
        // Here is an instance of the Mavon editor with many methods mounted on it
        const $vm = this.$refs.md
        // Insert the file name and file path into the current cursor position, which is a built-in method in mavon-Editor
        $vm.insertText($vm.getTextareaDom(),
          {
            prefix: ` [${file.name}] (${res.data.path}) `.subfix: ' '.str: ' '})})},Copy the code

Summary: That’s how mavon-Editor customizes toolbars! I’m just a struggling junior college student — Tianming, I hope to work together with you, as long as we work hard enough, our boss will be able to live the life he wants as soon as possible!