Reputation: 2153
I try to add somes text (tags) in Vuetify textarea from button.
<v-btn small flat @click.stop="insertTag('{{title}}', <model-name-here>)">+ Title</v-btn>
The method insertTag provide this:
this.$refs[model][0].focus()
I don't know how I can insert text to cursor position in textarea...
Upvotes: 2
Views: 3217
Reputation: 71
Kallan DAUTRICHE's answer is on the right track, but not quite what I needed (or what the OP needed I think).
You have to set the ref of the element so you can directly select the input element of your DOM to get/set selection details
Template:
<v-text-field v-model="model" ref="textField">
Script:
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));
}
},
});
Upvotes: 4
Reputation: 21
<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));
},
Upvotes: 2
Reputation: 36
I had the same problem to insert emoji in the right place in a text field. I found a quick fix, but after inserting my emoji, the cursor moves to the end of the input field. Maybe if you insert text and not a native emoji, you will not have my problem.
You have to set the id of the element and not its reference so you can directly select the input element of your DOM and take the attribute "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>
This is an old post but I hope this answer can help someone
Upvotes: 2