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
    })
  }
}
相关推荐
赵广陆1 小时前
SprinBoot+Vue宠物寄养系统的设计与实现
前端·vue.js·宠物
A黄俊辉A2 小时前
vue3中把封装svg图标为全局组件
前端·javascript·vue.js
老贾爱编程2 小时前
VUE实现刻度尺进度条
前端·javascript·vue.js
F2E_Zhangmo2 小时前
vue如何做到计算属性传参?
前端·javascript·vue.js
叫我小鹏呀3 小时前
vue3中el-table中点击图片放大时,被表格覆盖
前端·javascript·vue.js
四季予你663 小时前
vue2 和 vue3 的区别
前端·javascript·vue.js
炒毛豆4 小时前
vue3+ant design vue实现可编辑表格弹出气泡弹出窗~
前端·javascript·vue.js
寰宇软件4 小时前
vue组件注册
前端·javascript·vue.js
佩淇呢5 小时前
uniapp vue3 梯形选项卡组件
前端·vue.js·uni-app