App下載

vue使用vue-quill-editor富文本編輯器且將圖片上傳到服務(wù)器

猿友 2021-01-13 17:13:32 瀏覽數(shù) (2997)
反饋

一、準備工作

下載 vue-quill-editor

npm install vue-quill-editor --save  或者 yarn add vue-quill-editor

二、定義全局組件quill-editor

下載好 vue-quill-editor 后,我們需要定義一個全局組件,把這個組件名字命名為 quill-editor

1、定義template模板

<div>
   <quill-editor
       v-model="value"
       ref="myQuillEditor"
       :options="editorOption"
       @change="onEditorChange"
       >
   </quill-editor>
   <input type="file" hidden accept=".jpg,.png" ref="fileBtn" @change="handleChange" />
</div>

2、定義富文本選項配置

editorOption: {
   toolbar: [
      ['bold', 'italic', 'underline'],   //加粗、斜體、下劃線、刪除線, 'strike'
      ['blockquote', 'code-block'],   //引用、代碼塊
      [{ 'header': 1 }, { 'header': 2 }],  //H1 H2
      [{ 'list': 'ordered' }, { 'list': 'bullet' }],  //列表
      [{ 'script': 'sub' }, { 'script': 'super' }],   //上標、下標
      [{ 'indent': '-1' }, { 'indent': '+1' }],   //縮進
      [{ 'direction': 'rtl' }],    //文字編輯方向,從左到右還是從右到左
      [{ 'size': ['small', false, 'large', 'huge'] }],  //文字大小
      [{ 'header': [1, 2, 3, 4, 5, 6, false] }],  //選中的文字容器高度
      [{ 'font': [] }],   //字體樣式
      [{ 'color': [] }, { 'background': [] }],   //顏色、背景顏色
      [{ 'align': [] }],   //對齊方式
      ['clean'],   //清除選中文字的所有樣式
      ['link', 'image', 'video']   //超鏈接、圖片、視頻鏈接
  ],
}

三、相關(guān)方法

1、改變原有富文本編輯器上傳圖片綁定方法

mounted() {
   if (this.$refs.myQuillEditor) {
       //myQuillEditor改成自己的
       this.$refs.myQuillEditor.quill.getModule("toolbar").addHandler("image", this.imgHandler);
  }
},
methods:{
  imgHandler(state) {
      if (state) {
      //觸發(fā)input的單擊 ,fileBtn換成自己的
          this.$refs.fileBtn.click()
      }
  }
}

2、上傳事件

handleChange(e) {
   const files = Array.prototype.slice.call(e.target.files);
   if (!files) {
       return;
  }
   let formdata = new FormData();
   formdata.append("file_name", files[0].name);
   formdata.append("imgs", files[0]);
   //使用了axios請求
   this.axios({
       url: this.$store.state.baseUrl + 'upload/ueditorFile',
       method: 'post',
       data: formdata,
       headers: {'client-identity': localStorage.getItem('session_id')}
  }).then((res) => {
  //這里設(shè)置為空是為了聯(lián)系上傳同張圖可以觸發(fā)change事件
       this.$refs.fileBtn.value = "";
       if (res.data.code == 200) {
           let selection = this.$refs.myQuillEditor.quill.getSelection();
           //這里就是返回的圖片地址,如果接口返回的不是可以訪問的地址,要自己拼接
           let imgUrl = this.$store.state.baseUrl + res.data.data;
           imgUrl = imgUrl.replace(/\\/g,"/")  
//獲取quill的光標,插入圖片
           this.$refs.myQuillEditor.quill.insertEmbed(selection != null ? selection.index : 0, 'image', imgUrl)                
//插入完成后,光標往后移動一位
           this.$refs.myQuillEditor.quill.setSelection(selection.index + 1);
      }
  })
}

最后在父組件使用這個全局 quill 組件,并傳遞自己需要的相關(guān)參數(shù),就完成啦~


推薦好課:Vue.js三天學習實戰(zhàn)教程、Vue3.0新特性全面解析


0 人點贊