[Vue.js] Bootstrap-vue textarea.selectionStart is NaN or undefined

I’m trying to detect when the user is pressing the tab key, so I can insert spaces, instead of shifting the element focus.

The event handler is called correctly, but the value of both .selectionStart and .selectionEnd properties are either undefined or NaN. Is there something wrong with my code?

<b-form-textarea
id=”pythonCodeInput”
placeholder=”Write Python code here…”
v-model=”newQuestion.objects.code”
ref=”codeInput”
@keydown.native.tab=”keyDownInTextarea”>
</b-form-textarea>

Relevant code from keyDownInTextarea

let codeInput = this.$refs.codeInput; // Add 4 spaces let tabSize = 4; let tabPosition = codeInput.selectionStart; let textWithSpaces = codeInput.value.substring(0, tabPosition); for (let i = 0; i < tabSize; i++) textWithSpaces += “ “; textWithSpaces += codeInput.value.substring(tabPosition); I expect tabPosition to have an value showing where the cursor is, but the actual output is NaN or undefined. Solution : When you attached a ref to <b-form-textarea>, what you get is the reference to an instance of the <b-form-textarea> component and not the textarea element which you are trying to access. Refer to docs for more info. To access the actual <textarea> element, you can do it by accessing the inner$refs of the codeInput ref since under the hood, the textarea element has a ref called input.

To put it simply, it would look like this.

// this is a reference to the <b-form-textarea> component instance.
let codeInput = this.$refs.codeInput; // get the actual DOM element const textArea = codeInput.$refs.input;

See working example

Solution 2:

I’m new to vue.js so sry if I got something wrong.

Here is what I got after some testing. I replaced @keydown.native.tab with v-on:keydown.tab and that seems to work without any problems.

new Vue({
el: ‘textarea’,
methods: {
test: (e) => {
console.log(e.target.selectionStart);
}
}
})
<script src=”https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<textarea
id=”textarea”
v-on:keydown.tab=”test” ></textarea>