Insert character at Cursor position in VUE JS
<!-- tag -->
<textarea ref="yourTextarea" v-model.trim="txtContent" ......></textarea>
// methods:
insertSomething: function(insert) {
const self = this;
var tArea = this.$refs.yourTextarea;
// filter:
if (0 == insert) {
return;
}
if (0 == cursorPos) {
return;
}
// get cursor's position:
var startPos = tArea.selectionStart,
endPos = tArea.selectionEnd,
cursorPos = startPos,
tmpStr = tArea.value;
// insert:
self.txtContent = tmpStr.substring(0, startPos) + insert + tmpStr.substring(endPos, tmpStr.length);
// move cursor:
setTimeout(() => {
cursorPos += insert.length;
tArea.selectionStart = tArea.selectionEnd = cursorPos;
}, 10);
}
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