1. 程式人生 > >Vue +Element UI +vue-quill-editor 富文字編輯器及插入圖片自定義

Vue +Element UI +vue-quill-editor 富文字編輯器及插入圖片自定義

1.安裝

npm install vue-quill-editor --save

2.在main.js中引入

import VueQuillEditor  from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

Vue.use(VueQuillEditor);
3. template
<div>

      <!-- 圖片上傳元件輔助-->
      <el-upload
        class="avatar-uploader"
        :action="serverUrl"
        name="img"
        :headers="header"
        :show-file-list="false"
        :on-success="uploadSuccess"
        :on-error="uploadError"
        :before-upload="beforeUpload">
      </el-upload>
      <quill-editor
        v-model="content"
        ref="myQuillEditor"
        :options="editorOption"
        @change="onEditorChange($event)"
      >
      </quill-editor>
    </div>

4.js

<script>
  const toolbarOptions = [
    ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
    [{'header': 1}, {'header': 2}],               // custom button values
    [{'list': 'ordered'}, {'list': 'bullet'}],
    [{'indent': '-1'}, {'indent': '+1'}],          // outdent/indent
    [{'direction': 'rtl'}],                         // text direction
    [{'size': ['small', false, 'large', 'huge']}],  // custom dropdown
    [{'header': [1, 2, 3, 4, 5, 6, false]}],
    [{'color': []}, {'background': []}],          // dropdown with defaults from theme
    [{'font': []}],
    [{'align': []}],
    ['link', 'image'],
    ['clean']

  ]
  export default {
    data() {
      return {
        quillUpdateImg: false, // 根據圖片上傳狀態來確定是否顯示loading動畫,剛開始是false,不顯示
        content: null,
        editorOption: {
          placeholder: '',
          theme: 'snow',  // or 'bubble'
          modules: {
            toolbar: {
              container: toolbarOptions,
              handlers: {
                'image': function (value) {
                  if (value) {
                    // 觸發input框選擇圖片檔案
                    document.querySelector('.avatar-uploader input').click()
                  } else {
                    this.quill.format('image', false);
                  }
                }
              }
            }
          }
        },
        serverUrl: '/manager/common/imgUpload',  // 這裡寫你要上傳的圖片伺服器地址
header: { // token: sessionStorage.token } // 有的圖片伺服器要求請求頭需要有token } }, methods: { onEditorChange({editor, html, text}) {//內容改變事件 console.log("---內容改變事件---") this.content = html console.log(html) }, // 富文字圖片上傳前 beforeUpload() { // 顯示loading動畫 this.quillUpdateImg = true }, uploadSuccess(res, file) { // res為圖片伺服器返回的資料 // 獲取富文字元件例項 console.log(res); let quill = this.$refs.myQuillEditor.quill // 如果上傳成功 if (res.code == 200 ) { // 獲取游標所在位置 let length = quill.getSelection().index; // 插入圖片 res.url為伺服器返回的圖片地址 quill.insertEmbed(length, 'image', res.url) // 調整游標到最後 quill.setSelection(length + 1) } else { this.$message.error('圖片插入失敗') } // loading動畫消失 this.quillUpdateImg = false }, // 富文字圖片上傳失敗 uploadError() { // loading動畫消失 this.quillUpdateImg = false this.$message.error('圖片插入失敗') } } }

注意:serverUrl :檔案上傳地址不能直接寫全路徑,會出現跨域問題報錯。需要在conf/index.js 中 進行配置

module.exports = {
  dev: {
    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    host: 'localhost', // can be overwritten by process.env.HOST
    port: 8088, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
    autoOpenBrowser: true,
    cssSourceMap: true,
    proxyTable: {
      '/api': {
        target: 'http://localhost:18080/', //設定呼叫介面域名和埠號別忘了加http
        changeOrigin: true,
        pathRewrite: {
          '^/api': '/' //這裡理解成用‘/api’代替target裡面的地址,元件中我們調介面時直接用/api代替
          // 比如我要呼叫'http://0.0:300/user/add',直接寫‘/api/user/add’即可 代理後位址列顯示/
        }
      },
      '/manager': {
        target: 'http://localhost:18081/',
        changeOrigin: true,
        pathRewrite: {
          '^/manager': '/'
        }
      }
    }

  },

5.style

<style>
  .ql-editor.ql-blank, .ql-editor {
    height: 350px;
  }
</style>

6.後臺圖片上傳介面

 @RequestMapping(value = "/imgUpload")
    public Map<String ,Object> imgUpload(HttpServletRequest req, MultipartHttpServletRequest multiReq)
            throws IOException {
       
        FileOutputStream fos = new FileOutputStream(
                new File("E://fileupload//upload.jpg"));
        FileInputStream fs = (FileInputStream) multiReq.getFile("img").getInputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = fs.read(buffer)) != -1) {
            fos.write(buffer, 0, len);
        }
        fos.close();
        Map<String ,Object> map=new HashMap<>();
        map.put("code",200);
        map.put("msg","上傳成功");
        map.put("url","http://localhost:8080/tomcat.png");
        return map;//這裡只做返回值測試用,url 引數為圖片上傳後訪問地址。具體根據功能進行修改}

7.效果如下