在VUE JS中的Cursor位置插入字符 [英] Insert character at Cursor position in VUE JS

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

问题描述

我一直试图在textarea中准确插入光标所在的表情符号。我环顾了一下网页中的tos 如何在VUE JS中找不到任何特定内容。他们中的大多数都是普通的JS。

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.

我有这个代码

<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>

我的方法

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

显然,这段代码会添加字符(在我的情况下是表情符号)最后一个字符串。我需要一个纯粹的vuejs解决方案。
Vue中这类问题的最佳做法是什么?因为在网络中很少有基于vanilla JS或Jquery的解决方案。

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.

推荐答案

两个步骤:

1使用vue-way获取 textarea 元素:

1 get textarea element using a vue-way:

1.1添加 ref 在模板代码中输入 textarea 标记:

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

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

1.2在挂载挂钩之后获取此元素此组件:

1.2 get this element after mounted hook of this component:

let textarea = this.$refs.ta

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

2 get cursor position of textarea element.

let cursorPosition = textarea.selectionStart

以下是参考:< a href =https://vuejs.org/v2/api/#ref =noreferrer> ref

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆