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
    })
  }
}
相关推荐
挑战者6668883 分钟前
vue入门环境搭建及demo运行
前端·javascript·vue.js
程序猿ZhangSir2 小时前
Vue3 项目的基本架构解读
前端·javascript·vue.js
亲亲小宝宝鸭2 小时前
写了两个小需求,终于搞清楚了表格合并
前端·vue.js
Face3 小时前
路由Vue-router 及 异步组件
前端·javascript·vue.js
风之舞_yjf4 小时前
Vue基础(14)_列表过滤、列表排序
前端·javascript·vue.js
疯狂的沙粒5 小时前
uni-app 项目支持 vue 3.0 详解及版本升级方案?
前端·vue.js·uni-app
Lhuu(重开版5 小时前
Vue:Ajax
vue.js·ajax·okhttp
国家不保护废物6 小时前
从刀耕火种到现代框架:DOM编程 vs Vue/React 进化史
前端·vue.js·react.js
阿琳a_6 小时前
前端对WebSocket进行封装,并建立心跳监测
前端·javascript·vue.js·websocket
Am1nnn6 小时前
【Pinia】Pinia和Vuex对比
前端·javascript·vue.js