【问题标题】:VueJS/Vuetify - Add some text to focus position on textareaVueJS/Vuetify - 添加一些文本以将焦点放在 textarea 上
【发布时间】:2018-04-30 15:10:52
【问题描述】:

我尝试在按钮的 Vuetify 文本区域中添加一些文本(标签)。

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

insertTag 方法提供了这个:

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

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

【问题讨论】:

标签: vue.js focus vuetify.js


【解决方案1】:

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

您必须设置元素的 ref,以便您可以直接选择 DOM 的输入元素以获取/设置选择详细信息

模板:

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

        }
    },
});

【讨论】:

    【解决方案2】:

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

    您必须设置元素的 id 而不是它的引用,这样您就可以直接选择 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>
    

    这是一篇旧帖子,但我希望这个答案可以帮助某人

    【讨论】:

      【解决方案3】:
       <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));
      },
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-11-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多