vue、vue-quill-editor、七牛上傳圖片

image.png

一、下載安裝必須插件css

cnpm i vue-quill-editor -S
// 可拖拽圖片
cnpm i quill-image-drop-module -S
// 這兩個是改變圖片大小的
cnpm i quill-image-resize-module -S

二、引入html內容html

<div id='quillEditorQiniu'>
    <quill-editor
      :style="'width: '100%'"
      v-model="content"
      ref="myQuillEditor"
      :options="editorOption"
      @change="onEditorChange($event)"
    >
    </quill-editor>
    <Upload
      class="avatar-uploader"
      :accept="'image/*'"
      :action="'https://upload.qiniup.com'"
      name='file'
      :data="updateParams"
      :show-upload-list="false"
      :on-success="uploadSuccess"
      :on-error="uploadError"
      :before-upload="beforeUpload"
    >
    </Upload>

注意若是想看upload詳細講解能夠看我上一片文章http://www.javashuo.com/article/p-gshcarae-go.htmlvue

三、首先配置工具欄顯示圖標webpack

const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'],
  [{'color': []}, { 'size': fontSizeStyle.whitelist }],
  [{ list: 'ordered' }, { list: 'bullet' }],
  [{ indent: '-1' }, { indent: '+1' }],
  ['link', 'image']
]

四、這裏的其餘圖標都是系統給的,只有「size」字體選擇下拉框,是我本身配置的,由於默認只有三種字體大小,咱們須要擴展,在Quill上註冊字體:web

import { quillEditor } from 'vue-quill-editor'
// 富文本編輯器 quill editor 樣式
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import * as Quill from 'quill'
let fontSizeStyle = Quill.import('attributors/style/size')
fontSizeStyle.whitelist = ['12px', '14px', '16px', '20px', '24px', '36px']
Quill.register(fontSizeStyle, true)

五、使用配置項npm

data () {
    return {
        editorOption: {
        placeholder: '請輸入',
        theme: 'snow',
        modules: {
          toolbar: {
            container: toolbarOptions
          }
        }
      },
    }
}

六、還須要修改css文件,咱們最好建一個全局css覆蓋quill的css樣式segmentfault

.ql-editor{
  min-height:150px;
}
.ql-snow .ql-tooltip[data-mode=link]::before {
  content: "請輸入連接地址:";
}
.ql-snow .ql-tooltip.ql-editing a.ql-action::after {
    border-right: 0px;
    content: '保存';
    padding-right: 0px;
}
.ql-snow .ql-tooltip[data-mode=video]::before {
    content: "請輸入視頻地址:";
}
.ql-snow .ql-picker.ql-size .ql-picker-label::before,
.ql-snow .ql-picker.ql-size .ql-picker-item::before {
  content: '14px';
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value=small]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value=small]::before {
  content: '10px';
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value=large]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value=large]::before {
  content: '18px';
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value=huge]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value=huge]::before {
  content: '32px';
}

.ql-snow .ql-picker.ql-header .ql-picker-label::before,
.ql-snow .ql-picker.ql-header .ql-picker-item::before {
  content: '文本';
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="1"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="1"]::before {
  content: '標題1';
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="2"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="2"]::before {
  content: '標題2';
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="3"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="3"]::before {
  content: '標題3';
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="4"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="4"]::before {
  content: '標題4';
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="5"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="5"]::before {
  content: '標題5';
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="6"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="6"]::before {
  content: '標題6';
}

.ql-snow .ql-picker.ql-font .ql-picker-label::before,
.ql-snow .ql-picker.ql-font .ql-picker-item::before {
  content: '標準字體';
}
.ql-snow .ql-picker.ql-font .ql-picker-label[data-value=serif]::before,
.ql-snow .ql-picker.ql-font .ql-picker-item[data-value=serif]::before {
  content: '襯線字體';
}
.ql-snow .ql-picker.ql-font .ql-picker-label[data-value=monospace]::before,
.ql-snow .ql-picker.ql-font .ql-picker-item[data-value=monospace]::before {
  content: '等寬字體';
}
.ql-toolbar.ql-snow + .ql-container.ql-snow {
  border-bottom-left-radius: 5px;
  border-bottom-right-radius: 5px;
}
.ql-toolbar.ql-snow {
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
}
.ql-snow .ql-stroke,
.ql-snow .ql-picker {
  color: #999;
  stroke: #999;
}
.ql-snow .ql-fill, .ql-snow .ql-stroke.ql-fill {
  fill: #999;
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value='12px']::before, .ql-snow .ql-picker.ql-size .ql-picker-item[data-value='12px']::before {
  content: '12px';
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value='14px']::before, .ql-snow .ql-picker.ql-size .ql-picker-item[data-value='14px']::before {
  content: '14px';
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value='16px']::before, .ql-snow .ql-picker.ql-size .ql-picker-item[data-value='16px']::before {
  content: '16px';
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value='20px']::before, .ql-snow .ql-picker.ql-size .ql-picker-item[data-value='20px']::before {
  content: '20px';
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value='24px']::before, .ql-snow .ql-picker.ql-size .ql-picker-item[data-value='24px']::before {
  content: '24px';
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value='36px']::before, .ql-snow .ql-picker.ql-size .ql-picker-item[data-value='36px']::before {
  content: '36px';
}
.ql-container {
  font-size:14px;
}
到這裏咱們富文本編輯器的字體就配置好了,下來咱們配置插入圖片上傳七牛,並調整圖片的大小。

一、導入須要的js服務器

import { quillEditor } from 'vue-quill-editor'
import * as Quill from 'quill'
import { ImageDrop } from 'quill-image-drop-module'
import ImageResize from 'quill-image-resize-module'
Quill.register('modules/imageDrop', ImageDrop)
Quill.register('modules/imageResize', ImageResize)

二、配置build/webpack.dev.config/webpack.pro.config.js,plugins:[]中加入如下代碼iview

new webpack.ProvidePlugin({
  'window.Quill': 'quill/dist/quill.js',
  'Quill': 'quill/dist/quill.js'
})
這樣就能夠調整圖片尺寸了
接下來咱們將圖片上傳到七牛服務器,而且將地址插入到富文本編輯器中。

一、咱們監聽點擊富文本編輯器上面的圖片被單擊的時候,觸發咱們的上傳組件被單擊,打開上傳窗口。編輯器

mounted () {
    // 工具欄中的圖片圖標被單擊的時候調用這個方法
    let imgHandler = (state) => {
      if (state) {
        document.querySelector('.avatar-uploader input').click()
      }
    }
    // 當工具欄中的圖片圖標被單擊的時候
    this.$refs.myQuillEditor.quill.getModule('toolbar').addHandler('image', imgHandler)
  },

二、上傳組件,上傳圖片到七牛,成功之後獲取到上傳圖片的地址,插入到富文本編輯器中

<Upload
      class="avatar-uploader"
      :accept="'image/*'"
      :action="'https://upload.qiniup.com'"
      // 注意name必須是file,以前寫的img,七牛老報錯,說是multiple什麼的name必須是file。
      name='file'
      :data="updateParams"
      :show-upload-list="false"
      :on-success="uploadSuccess"
      :on-error="uploadError"
      :before-upload="beforeUpload"
    >

三、這裏:action是七牛服務器地址,咱們須要在beforeUpload()鉤子函數中傳遞兩個參數(token:後臺接口獲取,key:文件名稱),而後在successUpload()鉤子函數中獲取到上傳圖片地址,直接插入到富文本編輯器就能夠了

beforeUpload (request, file) {
      // 設置上傳參數
      this.updateParams.token = this.$store.state.upload_token
      this.updateParams.key = request.name
    },
uploadSuccess (res, file) {
      // file 返回的文件信息,也能夠在這裏調用七牛上傳。
      console.log(res, file, this.$store.getters.upload_url + res.key, 'success')
      // 上傳完成之後修改圖片地址,回顯到quill編輯器中
      let quill = this.$refs.myQuillEditor.quill
      let length = quill.getSelection() ? quill.getSelection().index : 0
      // 插入圖片  res.info爲服務器返回的圖片地址
      console.log(this.$store.getters.upload_url + file.name)
      // quill.insertEmbed(length, 'image', this.$store.getters.upload_url + file.name)
      quill.insertEmbed(length, 'image', this.$store.getters.upload_url + res.key)
      // 調整光標到最後
      quill.setSelection(length + 1)
    },
這樣就完成了vue + upload + quill 封裝富文本編輯器組件的全過程,下面是我封裝的組件的所有代碼,token是在$store中保存的。
<template>
  <div id='quillEditorQiniu'>
    <quill-editor
      :style="{width: width ? width: '100%'}"
      v-model="content"
      ref="myQuillEditor"
      :options="editorOption"
      @change="onEditorChange($event)"
    >
    </quill-editor>
    <Upload
      class="avatar-uploader"
      :accept="'image/*'"
      :action="'https://upload.qiniup.com'"
      name='file'
      :data="updateParams"
      :show-upload-list="false"
      :on-success="uploadSuccess"
      :on-error="uploadError"
      :before-upload="beforeUpload"
    >
    </Upload>
  </div>
</template>
<script>
import { quillEditor } from 'vue-quill-editor'
import * as Quill from 'quill'
import { ImageDrop } from 'quill-image-drop-module'
import ImageResize from 'quill-image-resize-module'
let fontSizeStyle = Quill.import('attributors/style/size')
fontSizeStyle.whitelist = ['12px', '14px', '16px', '20px', '24px', '36px']
Quill.register(fontSizeStyle, true)
Quill.register('modules/imageDrop', ImageDrop)
Quill.register('modules/imageResize', ImageResize)
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'],
  [{'color': []}, { 'size': fontSizeStyle.whitelist }],
  [{ list: 'ordered' }, { list: 'bullet' }],
  [{ indent: '-1' }, { indent: '+1' }],
  ['link', 'image']
]
// 自定義編輯器的工做條
export default {
  name: 'quill-editor-qiniu',
  components: {
    quillEditor,
    ImageResize
  },
  props: ['initValue', 'width'],
  created () {
    // 獲取初始化回顯內容
    this.content = this.initValue
    // 獲取上傳token
    this.$store.dispatch('uploadToken')
  },
  mounted () {
    // 工具欄中的圖片圖標被單擊的時候調用這個方法
    let imgHandler = (state) => {
      if (state) {
        document.querySelector('.avatar-uploader input').click()
      }
    }
    // 當工具欄中的圖片圖標被單擊的時候
    this.$refs.myQuillEditor.quill.getModule('toolbar').addHandler('image', imgHandler)
  },
  data () {
    return {
      content: '',
      editorOption: {
        placeholder: '請輸入',
        theme: 'snow',
        modules: {
          toolbar: {
            container: toolbarOptions
          },
          imageDrop: true,
          imageResize: {
            displayStyles: {
              backgroundColor: 'black',
              border: 'none',
              color: 'white'
            },
            modules: [ 'Resize', 'DisplaySize', 'Toolbar' ]
          }
        }
      },
      updateParams: {}
    }
  },
  watch: {
    initValue: function (newVal, oldVal) {
      this.content = newVal
    }
  },
  methods: {
    onEditorChange (event) {
      console.log(event, 'change')
      this.$emit('getEditorInfo', event)
    },
    beforeUpload (request, file) {
      // 設置上傳參數
      this.updateParams.token = this.$store.state.upload_token
      this.updateParams.key = request.name
    },
    // 上傳圖片成功
    uploadSuccess (res, file) {
      // file 返回的文件信息,也能夠在這裏調用七牛上傳。
      console.log(res, file, this.$store.getters.upload_url + res.key, 'success')
      // 上傳完成之後修改圖片地址,回顯到quill編輯器中
      let quill = this.$refs.myQuillEditor.quill
      let length = quill.getSelection() ? quill.getSelection().index : 0
      // 插入圖片  res.info爲服務器返回的圖片地址
      console.log(this.$store.getters.upload_url + file.name)
      // quill.insertEmbed(length, 'image', this.$store.getters.upload_url + file.name)
      quill.insertEmbed(length, 'image', this.$store.getters.upload_url + res.key)
      // 調整光標到最後
      quill.setSelection(length + 1)
    },
    // 上傳圖片失敗
    uploadError (res, file) {
      console.log(res, file, 'error')
    }
  }
}
</script>
<style scoped>
</style>

最後咱們這裏upload使用了iview的組件,使用的是action裏面的請求地址,若是不使用組件的action,咱們能夠經過七牛實例,在beforeUpload中請求數據。

......
import * as qiniu from 'qiniu-js'
......
 beforeUpload (file) {
    // 配置參數,file, key: file.name, token
      var observable = qiniu.upload(file, file.name, this.$store.state.upload_token)
      observable.subscribe({
        next (res) {
          console.log(res, 'r')
        },
        error (error) {
          console.log(error)
        },
        complete: (complete) => {
          console.log(complete, 'c')
          let quill = this.$refs.myQuillEditor.quill
          let length = quill.getSelection().index
          // 插入圖片  res.info爲服務器返回的圖片地址
          quill.insertEmbed(length, 'image', 'https://qiniutest.tech/' + complete.key)
          // 調整光標到最後
          quill.setSelection(length + 1)
        }
      })
    },
相關文章
相關標籤/搜索