VueJS/Vuetify - 添加一些文本到文本区域的焦点位置

VueJS/Vuetify - Add some text to focus position on textarea

我尝试通过按钮在 Vuetify 文本区域中添加一些文本 (tags)。

<v-btn small flat @click.stop="insertTag('{{title}}', <model-name-here>)">+ Title</v-btn>

insertTag 方法提供了这个:

this.$refs[model][0].focus()

我不知道如何将文本插入文本区域中的光标位置...

我在文本字段的正确位置插入表情符号时遇到了同样的问题。我找到了一个快速修复方法,但在插入我的表情符号后,光标移动到输入字段的末尾。也许如果你插入文本而不是原生表情符号,你就不会遇到我的问题。

您必须设置元素的 ID 而不是它的引用,这样您就可以直接 select 您的 DOM 的输入元素并获取属性 "selectionEnd"

<template>
    ...
    <v-text-field v-model="model" id="inputTextField">
    ...
</template>

<script/method>
   ...
   let out = <yourVariableText>
   let cursorIndex = document.getElementById('inputTextField').selectionEnd;
   out = out.substring(0, cursorIndex) + tagToInsert + out.substring(cursorIndex);
   ...
</script/method>

这是一个旧的 post 但我希望这个答案可以帮助别人

Kallan DAUTRICHE 的回答是正确的,但不是我需要的(或者我认为 OP 需要的)。

您必须设置元素的 ref,以便您可以直接 select 将 DOM 的输入元素 get/set selection details

模板:

<v-text-field v-model="model" ref="textField">

脚本:

export default Vue.extend({
    data: () => ({
        model: "",
    }),
    methods: {
        insertText(text) {

            // Get the input element by tag name, using the ref as a base for the search
            // This is more vue-friendly and plays nicer when you duplicate components
            const el = this.$refs.textField.querySelector("input");

            // Insert text into current position
            let cursorPos = el.selectionEnd; // Get current Position
            this.model =
                this.model.substring(0, cursorPos) +
                text +
                this.model.substring(cursorPos);

            // Get new cursor position
            cursorPos += text.length;

            // Wait until vue finishes rendering the new text and set the cursor position.
            this.$nextTick(() => el.setSelectionRange(cursorPos, cursorPos));

        }
    },
});
 <v-textarea label="Текст сообщения" v-model="text_sms" ref="ref_text_sms"></v-textarea>

 methods: {
insert() {
  const el = this.$refs.ref_text_sms.$el.querySelector("textarea");
  let cursorPos = el.selectionEnd;
  this.text_sms = this.text_sms.substring(0, cursorPos) + "my_test" +  this.text_sms.substring(cursorPos);
  cursorPos += this.text_sms.length;
  this.$nextTick(() => el.setSelectionRange(cursorPos, cursorPos));
},