我尝试使用方法setSelectionRange
更改光标在vuetify v-textarea
中的位置。
当我不操作textarea的v-model
属性引用的数据元素时,它会很好地工作。但是,如果我尝试先更改主体,然后再应用setSelectionRange
方法;光标直接移动到文本的末尾。
我附上了一个简化版本的代码段。一旦您在文本区域的任何地方按了退格键,光标就会移到索引2;但它会移至文字结尾。
但是,如果再次删除this.body
并退格,它将和平地移至索引2。
new Vue({
el: '#app',
data: {
body: ''
},
created () {
this.body = 'I am initial body. Hit backspace on somewhere if you want!'
},
methods: {
onBackspaceOrDeleteButtonKeydown (event) {
// disable default behavior
event.preventDefault()
let bodyTextArea = this.$refs.pourBody.$el.querySelector('textarea')
// COMMENT OUT THE NEXT LINE TO SEE THE CURSOR MOVES TO INDEX 2 ALWAYS
this.body = 'I am changed body. My cursor should have moved to index 2 anyways, but it goes to the end like >'
bodyTextArea.setSelectionRange(2, 2)
}
}
})
<!DOCTYPE html>
<html>
<head>
<link href='https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons' rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/vuetify/dist/vuetify.min.css" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">
</head>
<body>
<div id="app">
<v-app>
<v-content>
<v-container>
<v-textarea
ref="pourBody"
outline
v-model="body"
auto-grow rows="7"
@keydown.delete="onBackspaceOrDeleteButtonKeydown"
></v-textarea>
</v-container>
</v-content>
</v-app>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuetify/dist/vuetify.js"></script>
</body>
</html>
setSelectionRange
显然不喜欢身体变化。我该如何解决?
最佳答案
将setSelectionRange包装到setTimeout中,就像setTimeout(() => bodyTextArea.setSelectionRange(2, 2))
一样。将光标设置到所需位置并重置光标位置后,v模型会重新渲染值。您必须确保之后再调用setSelectionRange
。