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
    })
  }
}
相关推荐
@大迁世界21 小时前
Vue 设计模式 实战指南
前端·javascript·vue.js·设计模式·ecmascript
芭拉拉小魔仙21 小时前
Vue项目中如何实现表格选中数据的 Excel 导出
前端·vue.js·excel
用户785127814701 天前
从 0 到 1 落地淘宝商品 API 开发:手把手教你采集、分析与避坑(含完整可运行代码)
vue.js
鸿Hong1 天前
从事Vue开发之查漏补缺:深度选择器
vue.js
小小前端_我自坚强1 天前
vue提高技术 高级语法相关
前端·vue.js·前端框架
小小前端_我自坚强1 天前
Vue 3 使用心得
前端·javascript·vue.js
Keepreal4961 天前
使用Canvas绘制转盘
javascript·vue.js·canvas
ScriptBIN1 天前
Javaweb--Vue
前端·vue.js
前端Hardy1 天前
Vue 高效开发技巧合集:10 个实用技巧让代码简洁 50%+,面试直接加分!
前端·javascript·vue.js
@大迁世界1 天前
第03章: Vue 3 组合式函数深度指南
前端·javascript·vue.js·前端框架·ecmascript