使用方法
不管vue-quill-editor對接的是那個UI框架念逞,還是全部自己寫贩耐,其實使用方法都是一樣的。
- 首先都是先能將文件上傳至七牛
- 然后針對vue-quill-editor開發(fā)handlers方法,觸發(fā)上傳功能载慈,拿到回調(diào)值徽千,insert進入富文本苫费。
獲取七牛token上傳
region: 上傳區(qū)域,可以設置為undefined
具體參數(shù)解釋說明 參考文檔双抽,原文文檔寫得比較詳細百框。
// 上傳圖片typescript
import { getQNToken } from '@/assets/api/QiNiu' // 已經(jīng)寫好的請求token接口
const qiniu = require('qiniu-js')
const QNUpload = (file: any, prefix: string, name: string, next) => {
return new Promise(async (resolve, reject) => {
const putExtra = {
fname: name,
params: {},
mimeType: null
}
const config = {
useCdnDomain: false // 是否使用 cdn 加速域名
}
// 接口getQNToken會緩存token到sessionStorage,發(fā)現(xiàn)沒有重新請求
const token = sessionStorage.getItem('QNToken') || await getQNToken(***) // 獲取token
const n = name.replace('.', '_' + new Date().getTime() + '.') // 重新命名
const key = prefix ? (prefix + '/' + n) : n // 加上傳過來的前綴
const observable = qiniu.upload(file, key, token, putExtra, config) // 使用SDK方式發(fā)起請求
// next 是一個回調(diào)函數(shù)
observable.subscribe(next, (error) => {
reject(error)
}, (complete) => {
resolve(complete)
})
})
}
export default QNUpload
base64 to blob二進制
/**
* base64 to blob二進制
* @param {*} dataURI:string
*/
const dataURItoBlob = (dataURI) => {
const mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
const byteString = atob(dataURI.split(',')[1])
const arrayBuffer = new ArrayBuffer(byteString.length)
const intArray = new Uint8Array(arrayBuffer)
for (let i = 0; i < byteString.length; i++) {
intArray[i] = byteString.charCodeAt(i)
}
return new Blob([intArray], { type: mimeString })
}
上傳文件組件
<template>
<div class="upload">
<Icon type="md-add" />
<span v-show="width>0">{{width}} * {{height}}</span>
<input type="file" @change="uploadFile" :accept="mimeType"/>
<div class="progress" v-show="percent && percent !== 100">
<Progress :percent="percent" hide-info />
</div>
</div>
</template>
<script lang="ts">
import { Component, Vue, Emit, Prop } from 'vue-property-decorator'
import { dataURItoBlob } from '@/assets/common'
import QNUpload from '@/assets/api/upload'
interface QNReceive {
type: string,
data: object
}
@Component
export default class Upload extends Vue {
// 上傳路徑前綴
@Prop(String) readonly prefix!: string
@Prop(String) readonly field!: string
// 控制文件上傳大小
@Prop({ default: 1024 }) readonly size!: number
// 設置提示圖尺寸
@Prop({ default: 200 }) readonly width!: number
@Prop({ default: 200 }) readonly height!: number
// 組件層控制上傳類型牍汹,默認是圖片
@Prop({ default: 'image/png, image/jpeg, image/gif, image/jpg' }) readonly mimeType!: string
// 已上傳圖片大小占比
percent:number = 0
@Emit()
uploadFile (e) {
const files = e.target.files
if (!files.length) return
let keys: Array<any> = []
for (let i = 0, len = files.length; i < len; i++) {
const file = files[i]
const size = this.size
// 大小驗證
if (/image/g.test(file.type) && file.size / 1024 > size) {
this.$Message.info({ content: file.name + '大小不能超過' + size + 'KB', duration: 5 })
continue
}
// 讀取文件轉(zhuǎn)blob
const reader = new FileReader()
reader.addEventListener('load', (data: any) => {
const dataURI = data.target.result
const blob = dataURItoBlob(dataURI)
const name = file.name
const prefix = this.prefix
// 調(diào)取上傳方法
QNUpload(blob, prefix, name, (next) => {
// 上傳進度
this.percent = next.total.percent
}).then((data) => {
this.$emit('completeUpload', Object.assign(data, { field: this.field }))
}).catch(error => {
console.log(error)
})
})
reader.readAsDataURL(file)
}
}
}
</script>
<style lang="scss">
.upload {
width: 100%;
height: 80px;
position: relative;
border: 1px dashed #cccccc;
border-radius: 4px;
display: flex;
align-items: center;
justify-content: center;
input {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
cursor: pointer;
}
i {
font-size: 40px;
cursor: pointer;
}
.progress {
position: absolute;
bottom: 2px;
left: 0;
width: 100%;
height: 20px;
}
span {
position: absolute;
bottom: 0;
left: 0;
display: block;
width: 100%;
height: 20px;
line-height: 20px;
color: $grayColor;
text-align: center;
font-weight: bold;
}
}
</style>
vue-quill-editor富文本添加上傳圖片
使用組件的方式加載富文本琅翻,配置toolbar,添加handlers處理方法柑贞。最后完成插入圖片
這里只配置了一張一張圖片上傳方椎,稍微改一下,添加multiple="true"钧嘶,就可以選中多個文件上傳
<template>
<div>
<quill-editor style="height: 800px;" ref="myQuillEditor" v-model="Qcontent" :options="editorOption"></quill-editor>
<v-upload ref="upload" v-show="false" @completeUpload="getCompleteUpload" prefix="goodsDetail"></v-upload>
</div>
</template>
<script lang="ts">
import { Component, Vue, Emit, PropSync, Prop, Watch } from 'vue-property-decorator'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
import VUpload from '@/components/Upload.vue'
@Component({
components: {
quillEditor,
VUpload
}
})
export default class QuillEditor extends Vue {
@PropSync('content', { default: '' }) readonly Qcontent?: string
@Prop({ default: false }) readonly sendContent?: Boolean
@Watch('sendContent')
onSendContentChanged(val: boolean, oldVal: boolean) {
if (val) {
this.$emit('getContent', this.Quill.container.innerHTML)
}
}
QNHost = ****
Quill:any = ''
addRange: any = ''
uploadType = ''
editorOption = {
modules: {
toolbar: {
container: [
['bold', 'italic', 'underline'],
[{ 'header': 1 }, { 'header': 2 }],
[{ 'list': 'ordered' }, { 'list': 'bullet' }],
[{ 'indent': '-1' }, { 'indent': '+1' }],
[{ 'size': ['small', false, 'large', 'huge'] }],
[{ 'header': [1, 2, 3, 4, 5, 6, false] }],
[{ 'color': [] }],
[{ 'font': [] }],
[{ 'align': [] }],
['clean'],
// 新增image棠众,使用自帶的icon,添加新的handlers
['image']
],
handlers: {
// 點擊 image會調(diào)取方法imgHandler
image: this.imgHandler
}
}
}
}
mounted () {
this.imgHandler()
}
@Emit()
imgHandler () {
const Quill: any = (this.$refs.myQuillEditor as Vue & {quill: () => any}).quill
this.Quill = Quill
const toolbar = Quill.getModule('toolbar')
const upload: any = this.$refs.upload
toolbar.addHandler('image', () => {
// 獲取當前鼠標位置
this.addRange = Quill.getSelection()
// 觸發(fā)上傳有决,可以單獨寫input直接觸發(fā)闸拿,這里使用封裝的組件
upload.$el.getElementsByTagName('input')[0].click()
})
}
@Emit()
getCompleteUpload (data) {
const index = this.addRange.index || 0
// 上傳成功拿到返回值,插入富文本
this.Quill.insertEmbed(index, 'image', this.QNHost + data.key)
}
}
</script>
總結(jié)
quill-editor 開發(fā)擴展還是很好開發(fā)的书幕。
一直有個疑問就是:quill-editor自己整了一套數(shù)據(jù)接口delta新荤,通過quill.getContents()獲取到delta,這個delta怎么展示在沒有引入這個包的界面上台汇?
現(xiàn)在我的辦法是:直接獲取container的innerHTML
不知還有更好的辦法沒苛骨?