<el-input
ref="editorRef"
v-model="valueHtml"
type="textarea"
:rows="4"
placeholder="请输入内容"
@keydown="handleKeyDown"
>
</el-input>
js逻辑
import { ref, nextTick } from 'vue'
const currentEvent = ref()
const valueHtml = ref('')
const editorRef = ref()
const handleKeyDown = ($event: Event) => {
const event = $event as KeyboardEvent
currentEvent.value = event.target as HTMLInputElement
// 定义组合键 Map
const shortCutKeys: (keyof KeyboardEvent)[] = ['metaKey', 'altKey', 'ctrlKey', 'shiftKey']
const isEnterKey = event.key === 'Enter'
const isShortcutKeys = shortCutKeys.some((item) => event[item])
if (isEnterKey && isShortcutKeys) {
// 获取光标位置
const cursorPosition = currentEvent.value.selectionStart
// 拆分成两段文本
const textBeforeCursor = valueHtml.value.slice(0, cursorPosition)
const textAfterCursor = valueHtml.value.slice(cursorPosition)
// 合并为带有换行符的新文本
const newText = textBeforeCursor + '\n' + textAfterCursor
// 更新输入框的值
valueHtml.value = newText
// 文本编辑器的高度发生变化后
nextTick(() => {
// 高度变化 自动滚动到底部
const editor = editorRef.value.textarea
editorRef.value.textarea.scrollTop = editor.scrollHeight
// 设置光标位置为: start 和 end 相同,光标会移动到换行符后面的新行首
currentEvent.value.setSelectionRange(cursorPosition + 1, cursorPosition + 1)
})
} else if (event.key === 'Enter') {
// 阻止掉 Enter 的默认换行行为
event.preventDefault()
// do yourself things for example send
}
}
else if (event.key === 'Enter') {
// 阻止掉 Enter 的默认换行行为
event.preventDefault()
}
const editor = editorRef.value.textarea
editorRef.value.textarea.scrollTop = editor.scrollHeight