vue项目中vue-quill-editor自定义图片上传

1、下载


npm install vue-quill-editor --save

2、在main.js中引入


// 导入富文本编辑器
import VueQuillEditor from 'vue-quill-editor'
// 将富文本编辑器,注册为全局可用组件
Vue.use(VueQuillEditor)

3、使用

// 导入富文本编辑器样式
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import {
    
     quillEditor } from 'vue-quill-editor'

components: {
    
    
    quillEditor
}

<quill-editor
    class="ql-editor"
    v-model="enterpriseForm.content"
    ref="myQuillEditor"
    :options="editorOption"
    @change="onEditorChange($event)"
/>
<input type="file" hidden accept=".jpg,.png" ref="fileBtn" @change="handleUpload" />

data() {
    
    
	return {
    
    
		enterpriseForm: {
    
    
			content: ""
		},
		editorOption: {
    
    
        	modules: {
    
    
          		toolbar: [
            		['bold', 'italic', 'underline', 'strike'],
            		[{
    
    'size': ['small', false, 'large', 'huge']}],
            		[{
    
    'font': []}],
            		[{
    
    'align': []}],
            		[{
    
    'list': 'ordered'}, {
    
    'list': 'bullet'}],
            		[{
    
    'indent': '-1'}, {
    
    'indent': '+1'}],
            		[{
    
    'header': 1}, {
    
    'header': 2}], 
            		['image'],
            		[{
    
    'direction': 'rtl' }],    //文字编辑方向,从左到右还是从右到左
            		[{
    
     'color': [] }, {
    
     'background': [] }] 
          		]
        	},
        	placeholder: '请输入内容...'
      	},
	}
}



mounted() {
    
    
    if (this.$refs.myQuillEditor) {
    
    
      this.$refs.myQuillEditor.quill.getModule("toolbar").addHandler("image", this.imgHandler);
    }
},
computed: {
    
    
    editor() {
    
    
      return this.$refs.myQuillEditor.quill
    }
},
methods: {
    
    
	imgHandler(state) {
    
    
      if (state) {
    
    
        this.$refs.fileBtn.click()
      }
    },
    handleUpload(e) {
    
    
      const files = Array.prototype.slice.call(e.target.files);
      if (!files) {
    
    
        return
      }
      let formdata = new FormData();
      formdata.append("file", files[0]);
      uploadFile(formdata)
      .then(res => {
    
    
        if (res.fileUrl) {
    
    
          let selection = this.$refs.myQuillEditor.quill.getSelection();
          //这里就是返回的图片地址,如果接口返回的不是可以访问的地址,要自己拼接
          let imgUrl = res.fileUrl;  
          //获取quill的光标,插入图片 
          this.$refs.myQuillEditor.quill.insertEmbed(selection != null ? selection.index : 0, 'image', imgUrl)                 
          //插入完成后,光标往后移动一位 
          this.$refs.myQuillEditor.quill.setSelection(selection.index + 1);
        }
      })
    },
    onEditorChange({
    
     quill, html, text }) {
    
    
      console.log('editor change!', quill, html, text)
    },
}

猜你喜欢

转载自blog.csdn.net/lannieZ/article/details/114638607