本文介绍了在 VUE JS 中的 Cursor 位置插入字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图在 textarea 中准确插入光标所在的位置.我在网上查看了 how tos 找不到任何特定于 VUE JS 的内容.他们中的大多数都是纯JS.

我有这个代码

<click-outside :handler="handleClickOutside"><选择器设置 =信使"title="选择你的表情符号..."表情符号=point_up"@click="addEmoji":emoji-size="16"></picker></click-outside>

<textarea id="greeting_text_input" class="form-control"类型=文本"v-model="greeting_text"行=8"必需的placeholder="Hi {first-name}!欢迎使用我们的机器人.单击获取开始"按钮开始></textarea>

我的方法

addEmoji(emoji){this.greeting_text += emoji.native;this.showPicker = !this.showPicker;}

显然,此代码会将字符(在我的情况下为表情符号)添加到字符串的最后一个.我需要一个纯 vuejs 解决方案.Vue 中此类问题的最佳实践是什么?因为网络中几乎没有基于 vanilla JS 或 Jquery 的解决方案.

解决方案

两步:

1 使用 vue 方式获取 textarea 元素:

1.1 将 ref 属性添加到模板代码中的 textarea 标签:

1.2 在这个组件的mounted钩子之后得到这个元素:

let textarea = this.$refs.ta

2 获取textarea元素的光标位置.

让 cursorPosition = textarea.selectionStart

这里是参考:ref

I have been trying to insert emoji in textarea exactly where the cursor is at. I looked around how tos in the web could not find anything specific in VUE JS. Most of them are in plain JS.

I have this Code

<div class="picker" v-show="showPicker">
    <click-outside :handler="handleClickOutside">
        <picker
            set ="messenger"
            title="Pick your emoji…"
            emoji="point_up"
            @click="addEmoji"
            :emoji-size="16"
        >
        </picker> 
    </click-outside>
</div>

<textarea id="greeting_text_input" class="form-control"
    type="text" 
    v-model="greeting_text"
    rows="8"
    required
    placeholder="Hi {first-name}! Welcome to our bot. Click on the ‘Get 
    Started’ button to begin
">
</textarea>

My Method

addEmoji(emoji){
        this.greeting_text += emoji.native;
        this.showPicker = !this.showPicker;
    }

Obviously, this code will add the character (emoji, in my case) to the last of the string. I need a pure vuejs solution for this. What would be the best practise for this kind of problem in Vue? as there are few solutions in the web that based either in vanilla JS or Jquery.

解决方案

Two steps:

1 get textarea element using a vue-way:

1.1 Add ref attrbute to textarea tag in your template code:

<textarea ref="ta"></textarea>

1.2 get this element after mounted hook of this component:

let textarea = this.$refs.ta

2 get cursor position of textarea element.

let cursorPosition = textarea.selectionStart

Here is reference: ref

这篇关于在 VUE JS 中的 Cursor 位置插入字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 11:31