首先封装一下图片上传方法(纯前端):
import * as qiniu from 'qiniu-js'export function uploadFile(file,token) {let fileNameLen = file.name.length;let startPos = file.name.lastIndexOf(".");//文件名const key = new Date().getTime() + '_' + file.name.substring(startPos,fileNameLen);const config = {useCdnDomain: true,region: qiniu.region.z0,forceDirect: true // 是否上传全部采用直传方式};const putExtra = {fname: file.name,mimeType: ['image/png', 'image/jpeg', 'image/gif']};return qiniu.upload(file, key, token, putExtra, config);
}
页面部分:
<template><VueEditor:editorOptions="editorSettings"v-model="actForm.detail"useCustomImageHandler@image-added="handleImageAdded"></VueEditor>
</template>
js部分:
<script>
//引入刚刚封装好的方法
import { uploadFile } from "@/utils/uploaderHelper.js"export default {data(){return{detail:'',editorImg: null,editorUrl: null,editorSettings:{modules:{clipboard:{matchers: [[Node.ELEMENT_NODE, this.handleCustomMatcher]]}}}}},created(){//页面载入时调用后端接口获取一下上传token},methods:{handleImageAdded(file, Editor, cursorLocation, resetUploader) {uploadFile(file,this.qiniuData.token).subscribe({next: (result) => {console.log(result);},error: (err) => {console.log(err)},complete: (e) => {this.editorImg = e.key;this.editorUrl = `https://scdn.usale.cn/${this.editorImg}`Editor.insertEmbed(cursorLocation, "image", this.editorUrl);resetUploader();},});},handleCustomMatcher(node, Delta) {let ops = []Delta.ops.forEach(op => {if (op.insert && typeof op.insert === 'string') {// 如果粘贴了图片,这里会是一个对象,所以可以这样处理ops.push({insert: op.insert,})}else{this.$message({message:'不允许粘贴图片,请手动上传',type:'warning'})}})Delta.ops = opsreturn Delta},}}
</script>
效果如下