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
    })
  }
}
相关推荐
前端赵哈哈8 分钟前
Vite 图片压缩的 4 种有效方法
前端·vue.js·vite
风中凌乱的L22 分钟前
vue 一键打包上传
前端·javascript·vue.js
GHOME26 分钟前
Vue2与Vue3响应式原理对比
前端·vue.js·面试
lumi.1 小时前
2.3零基础玩转uni-app轮播图:从入门到精通 (咸虾米总结)
java·开发语言·前端·vue.js·微信小程序·uni-app·vue
小蒜学长3 小时前
vue家教预约平台设计与实现(代码+数据库+LW)
java·数据库·vue.js·spring boot·后端
chxii6 小时前
6.3Element UI 的表单
javascript·vue.js·elementui
张努力6 小时前
从零开始的开发一个vite插件:一个程序员的"意外"之旅 🚀
前端·vue.js
chxii6 小时前
6.4 Element UI 中的 <el-table> 表格组件
vue.js·ui·elementui
Adler_hu8 小时前
cli项目页面白屏时间优化
vue.js·webpack
Adler_hu8 小时前
高复用性组件封装指南
前端·vue.js