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)
    },
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值