Vue:使用v-model绑定的textarea在光标处插入指定文本

一、问题描述

使用v-model绑定的textarea如果需要改变其内容,一般只要改变v-model对应的变量即可,但如果需要在textarea的当前光标位置插入指定文本,那就需要操作DOM了。于是我们写了一段js:

const insertTextAtCursor = (text) => {
  const textarea = document.querySelector('textarea')
  if (textarea) {
    const startPos = textarea.selectionStart
    const endPos = textarea.selectionEnd
    const value = textarea.value

    const beforeText = value.substring(0, startPos)
    const afterText = value.substring(endPos, value.length)
    const newValue = beforeText + text + afterText
    textarea.value = newValue
    textarea.selectionStart = textarea.selectionEnd = startPos + text.length
  }
}

但如果直接调用上述代码的insertTextAtCursor 函数,就会发现一些古怪的现象,比如下面点击[插入客户昵称],就会在textarea的当前光标处插入指定文本,但实际插入却不理想:
请添加图片描述

二、解决方案

上述问题产生的原因跟textarea.value与v-model直接产生了冲突,于是只要改一下代码:

const insertTextAtCursor = (text) => {
  const textarea = document.querySelector('textarea')
  if (textarea) {
    const startPos = textarea.selectionStart
    const endPos = textarea.selectionEnd
    const value = textarea.value

    const beforeText = value.substring(0, startPos)
    const afterText = value.substring(endPos, value.length)
    const newValue = beforeText + text + afterText
    form.value.next_visit_content = newValue

    nextTick(() => {
      textarea.selectionStart = textarea.selectionEnd = startPos + text.length
    })
  }
}

猜你喜欢

转载自blog.csdn.net/q1003675852/article/details/142254311