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
    })
  }
}
相关推荐
花菜会噎住5 小时前
Vue3核心语法进阶(computed与监听)
前端·javascript·vue.js
I'mxx5 小时前
【vue(2)插槽】
javascript·vue.js
花菜会噎住5 小时前
Vue3核心语法基础
前端·javascript·vue.js·前端框架
练习前端两年半7 小时前
Vue3 源码深度剖析:有状态组件的渲染机制与生命周期实现
前端·vue.js
533_10 小时前
[vue3 echarts] echarts 动态数据更新 setInterval
vue.js·echarts
jstart千语11 小时前
【vue】创建响应式数据ref和reactive的区别
前端·javascript·vue.js
盗德11 小时前
Vue渲染引擎的范式革命:从虚拟DOM到Vapor模式
前端·vue.js
Dolphin_海豚12 小时前
vapor 的 IR 是如何被 generate 到 render 函数的
前端·vue.js·vapor
初遇你时动了情13 小时前
JS中defineProperty/Proxy 数据劫持 vue3/vue2双向绑定实现原理,react 实现原理
javascript·vue.js·react.js