2.5.16
https://jsfiddle.net/50wL7mdz/211543/
If I modify the model of an input a caret resets.
In my example, If you place a cursor between "Hello" and "World", and remove the dot, the cursor will reset to the end.
I know I could change a text from "Hello.World" to "Something", and then vue would have no idea where to put the caret after the modification, but apart from using pure, non-vue, plain-old-javascript way, there's no way to handle this caret position.
My final result is that I don't want to alow the user to type two dots one right after the other, so this "Hello..World" is forbidden, and it needs to be changed to this "Hello.World". Problem is, I can't control the caret using vue, can you guys help?
Way to control the caret
No way to control the caret
This is not really related to Vue. When setting the value of an input, the cursor resets, but you can read it before and set it on a nextTick: https://jsfiddle.net/ky2dbahh/
watch: {
message() {
const pos = this.$refs.input.selectionStart -1
const message = this.message.replace(/[^a-z]/gi, '');
if (this.message !== message) {
this.$nextTick(() => {
this.$refs.input.selectionEnd = pos
})
}
this.message = message
}
}
Thanks @posva for your solution, we worked this out this way:
methods: {
updateValue (updatedValue) {
console.log('Update', updatedValue)
this.$emit('input', updatedValue.replace(/ /g, '').replace(')', '').replace('(', '').replace(/_/g, '').replace('+', ''))
this.$nextTick(() => {
let inputLength = this.$refs.inputRef.$refs.input.value.toString().length
if (inputLength === 16) {
this.$refs.inputRef.$refs.input.selectionEnd = inputLength
this.$refs.inputRef.$refs.input.selectionStart = inputLength
}
})
}
}
Most helpful comment
This is not really related to Vue. When setting the value of an input, the cursor resets, but you can read it before and set it on a
nextTick: https://jsfiddle.net/ky2dbahh/