演示
聊天輸入框 組件
src/components/ChatInput/index.vue
<template>
<div class="chat-input">
<div class="left">
<div
id="editor"
ref="editor"
contenteditable="true"
:class="editorClass"
:style="editorStyle"
@paste.prevent="handlePaste($event)"
@keyup="handleKeyUp($event)"
@keydown="handleKeyDown($event)"
>
<br>
</div>
<div><i v-show="loading" class="el-icon-loading" /></div>
</div>
</div>
</template>
<script>
/**
* 聊天輸入框
* events
* change function(value)
* enter function
*
* methods
* clean function
* focus function
*/
import axios from 'axios'
export default {
name: 'ChatInput',
props: {
editorClass: {
type: String,
default: ''
},
editorStyle: {
type: Object,
default: () => ({})
},
imgShowWidth: { // 聊天輸入框中粘貼的圖片顯示的寬度
type: Number,
default: 50
},
imgShowHeight: { // 聊天輸入框中粘貼的圖片顯示的高度
type: Number,
default: 50
},
uploadUrl: {
type: String,
default: 'https://imio.jd.com/uploadfile/file/uploadImg.action'
},
name: { // 上傳 表單 name
type: String,
default: 'upload'
},
enter: { // 是否支持回車, 目前還有個 bug 中文輸入后,在結尾回車,需要回車兩次
type: Boolean,
default: false
}
},
data() {
return {
msgList: [],
loading: false
}
},
methods: {
async handlePaste(event) {
const pasteResult = this.handlePastePlainText(event.clipboardData)
if (pasteResult) return
await this.handlePasteImageFile(event.clipboardData)
},
handleKeyUp(event) {
const childNodes = event.target.childNodes
this.emitChange(childNodes)
if (event.keyCode === 13) {
this.$emit('enter')
}
},
handleKeyDown(event) {
if (event.keyCode === 13) { // 禁止換行默認行為
event.preventDefault()
if (this.enter) {
const oBr = document.createElement('br')
this.cursorInsert(oBr)
}
}
},
// 去格式粘貼 文本
handlePastePlainText(clipboardData) {
const text = clipboardData.getData('text/plain')
if (text) {
const textNode = document.createTextNode(text)
this.cursorInsert(textNode)
return true
}
return false
},
// 粘貼圖片
async handlePasteImageFile(clipboardData) {
const img = this.getPasteImageFile(clipboardData.files)
if (!img) return
const uploadRes = await this.uploadChatImg(img)
if (!uploadRes) {
this.$message.error('圖片上傳失敗,請重新上傳')
return
}
const oImage = await this.getImageObject(uploadRes, this.imgShowWidth, this.imgShowHeight)
this.cursorInsert(oImage)
// 光標處插入 image 后,重新出發 emit 時間
const oEditor = this.$refs.editor
this.emitChange(oEditor.childNodes)
},
emitChange(editorChildNodes) {
const oldMsgList = JSON.parse(JSON.stringify(this.msgList))
this.msgList = [] // 重置
for (let i = 0; i < editorChildNodes.length; i++) {
if (editorChildNodes[i].nodeType === 1 && editorChildNodes[i].nodeName === 'BR') { // 處理回車
const lastMsg = this.msgList[this.msgList.length - 1]
if (lastMsg?.type === 'text') {
lastMsg.content += '\n'
}
} else if (editorChildNodes[i].nodeType === 3 && editorChildNodes[i].nodeValue) {
const lastMsg = this.msgList[this.msgList.length - 1]
if (lastMsg?.type === 'text') {
lastMsg.content += editorChildNodes[i].nodeValue
} else {
this.msgList.push({
type: 'text',
content: editorChildNodes[i].nodeValue
})
}
} else if (editorChildNodes[i].nodeType === 1 && editorChildNodes[i].nodeName === 'IMG') {
const dataset = editorChildNodes[i].dataset
this.msgList.push({
type: 'image',
url: editorChildNodes[i].src,
width: +dataset.width,
height: +dataset.height
})
}
}
if (!this.msgList.length && !oldMsgList.length) {
return
}
this.$emit('change', [...this.msgList])
},
// 光標處插入節點
cursorInsert(node) {
// 獲取光標范圍
const selObj = window.getSelection()
const range = selObj.getRangeAt(0)
// 光標處插入節點
range.insertNode(node)
// 取消insert node 后的選中狀態,將光標恢復到 insert node 后面
range.collapse(false)
},
getPasteImageFile(clipboardDataFiles) {
if (!clipboardDataFiles.length) {
console.log('沒有要粘貼的文件')
return null
}
// 剪切版中選擇的(用戶第一個點的在尾)第一張圖片
const clipboardDataFileList = Array.from(clipboardDataFiles || [])
let firstSelectedImage = null
clipboardDataFileList.forEach(file => {
if (!file.type.match(/image\//i)) {
return
}
firstSelectedImage = file
})
/**
* 這里的 firstSelectedFile 對象就是和 <input type="file" /> onchange 時 一樣的 文件對象
* */
return firstSelectedImage
},
/**
* 上傳聊天圖片
* @param file
* @return {Promise<null|{width: number, height: number, length: number, md5: string, path: string}>}
*/
async uploadChatImg(file) {
const formData = new FormData()
formData.append(this.name, file)
this.loading = true
try {
const resp = await axios.post(this.uploadUrl, formData)
if (resp.status === 200 && resp.data.code === 0) {
return resp.data
}
return null
} catch (e) {
return null
} finally {
this.loading = false
}
},
// 獲取一個 image object
getImageObject(uploadRes, showWidth, showHeight) {
const oImage = new Image(showWidth, showHeight)
const datasetFields = ['width', 'height']
datasetFields.forEach(field => {
oImage.setAttribute(`data-${field}`, uploadRes[field])
})
oImage.src = uploadRes.path
return oImage
},
// 清除 輸入框
clean() {
this.$refs.editor.innerHTML = ''
},
// 輸入框 焦點
focus() {
this.$refs.editor.focus()
}
}
}
</script>
<style scoped lang="scss">
.chat-input {
display: flex;
border: 1px solid #dcdfe6;
.left {
width: 100%;
div:nth-of-type(1) {
padding: 4px;
width: 300px;
min-height: 100px;
outline: none;
}
}
}
</style>
組件使用實例
<template>
<div>
<chat-input
ref="chat-input"
:editor-style="{width: '100%'}"
@change="handleChatInputChange"
@enter="handleChatSend"
/>
</div>
</template>
<script>
import ChatInput from '@/components/ChatInput'
export default {
name: 'UseDemo',
components: { ChatInput },
data() {
return {
chatInputValue: []
}
},
mounted() {
// setTimeout(() => {
// this.chatInputFocus()
// this.chatInputClean()
// }, 3000)
},
methods: {
// 獲取焦點
chatInputFocus() {
this.$refs['chat-input'].focus()
},
// 清空內容
chatInputClean() {
this.$refs['chat-input'].clean()
},
handleChatInputChange(value) {
console.log('輸入框的值變化', value)
this.chatInputValue = value ?? []
},
async handleChatSend() {
console.log('您按了 Enter 鍵')
// ... 可用來 調接口 發送數據到后台
}
}
}
</script>
<style scoped>
</style>
參考
js實現ctrl+v粘貼上傳圖片(兼容chrome、firefox、ie11)