gpt4 book ai didi

javascript - Vuetify - 当模型更改时,如何使 setSelectionRange(int, int) 在 v-textarea 中工作

转载 作者:行者123 更新时间:2023-12-03 01:07:30 24 4
gpt4 key购买 nike

我尝试使用方法setSelectionRange更改 vuetify 中光标的位置 v-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 显然不喜欢 body 变化。

我该如何解决这个问题?

最佳答案

将 setSelectionRange 包装到 setTimeout 中,如下所示 setTimeout(() => bodyTextArea.setSelectionRange(2, 2))。将光标设置到所需位置并重置光标位置后,v-model 会重新渲染值。您必须确保之后调用 setSelectionRange

关于javascript - Vuetify - 当模型更改时,如何使 setSelectionRange(int, int) 在 v-textarea 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52333594/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com