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

Vuetify - How to make setSelectionRange(int, int) work in v-textarea when its model is changed

我尝试使用方法setSelectionRange to change the position of the cursor in a vuetify v-textarea

当我 不操作 由文本区域的 v-model 属性引用的数据元素时,它工作得很好。但是,如果我尝试先更改 body,然后应用 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

除了givehug的方案你还可以做

this.$nextTick(() => {
   bodyTextArea.setSelectionRange(2, 2))
})