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
    })
  }
}
相关推荐
汝生淮南吾在北几秒前
SpringBoot3+Vue3个人健康管理网站
vue.js·spring boot·毕业设计·毕设
靓仔建4 分钟前
用tdesign-vue-next的t-tree-select做个下拉单选框
javascript·vue.js·tdesign
zhengxianyi51512 小时前
只需3句让Vue3 打包部署后通过修改配置文件修改全局变量——实时生效
vue.js·前后端分离·数据大屏·ruoyi-vue-pro优化
QQ40220549616 小时前
python基于vue的大学生课堂考勤系统设计与实现django flask pycharm
vue.js·python·django
WX-bisheyuange19 小时前
基于SpringBoot的交通管理在线服务系统
前端·javascript·vue.js·毕业设计
+VX:Fegn08951 天前
计算机毕业设计|基于springboot + vue校园实验室管理系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
烤麻辣烫1 天前
Web开发概述
前端·javascript·css·vue.js·html
计算机程序设计小李同学1 天前
基于Web和Android的漫画阅读平台
java·前端·vue.js·spring boot·后端·uniapp
干前端1 天前
Message组件和Vue3 进阶:手动挂载组件与 Diff 算法深度解析
javascript·vue.js·算法
zhengxianyi5151 天前
Vue2 打包部署后通过修改配置文件修改全局变量——实时生效
前端·vue.js·前后端分离·数据大屏·ruoyi-vue-pro