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
    })
  }
}
相关推荐
Cobyte2 小时前
23.Vue Vapor 组件 attrs 的实现
前端·javascript·vue.js
柯克七七4 小时前
给老项目加了 TypeScript,本来只想自己爽,结果全公司代码审查标准被我抬高了
前端·vue.js·typescript
自然 醒6 小时前
前端如何实现在线预览office常见文件功能?
前端·vue.js
肉肉不吃 肉6 小时前
前端调试跨域如何解决
前端·vue.js
卓怡学长7 小时前
w268基于springboot + vue 物流系统
java·数据库·vue.js·spring boot·spring·intellij-idea
迅速的自行车1 天前
从一段模板说起
前端·javascript·vue.js
阿奇__1 天前
uniapp微信小程序图片上传含回显组件(拍照,相册)
前端·javascript·vue.js
前端甜糖1 天前
前端如何实现在线预览office常见文件功能?
前端·vue.js
ljs6482739511 天前
智慧商城(Smart Mall):基于 Spring Boot + Vue 3 的现代化电商平台实战
linux·vue.js·spring boot·后端
析数塔1 天前
2026前端框架深度解析:React Compiler、Angular Zoneless、Vue 3.5重写游戏规则
前端·vue.js·react.js