我尝试使用setSelectionRange
方法在vuetify v-textarea
中更改光标的位置。
当我不操纵textarea的v-model
属性引用的数据元素时,它运行良好。但是,如果我先尝试更改身体,然后应用setSelectionRange
方法;光标直接移动到文本的末尾。
我附上了一个简化版的片段。一旦你在textarea的任何地方点击退格键,光标就会移动到索引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-model将重新渲染值。你必须确保你之后打电话给setSelectionRange
。