Javascript:更改输入值时设置光标位置

Jon*_*sot 4 javascript input caret vue.js

当您输入公式时,我试图在我的应用程序中重现类似于 Microsoft Excel / Google Sheets 的用户体验,并且您可以使用不同的公式和变量来自动完成下拉菜单。

为此,在验证自动完成功能后,我希望能够控制光标的位置。

例如,如果我输入=sum(变量1,变量2),则在变量2自动完成时,光标应该位于最后一个括号之前,而不是在最后。

我了解如何使用javascript设置光标的位置,问题是因为我同时修改输入的值并设置光标位置,后者不起作用。

我用更简单的上下文重现了问题: https ://jsfiddle.net/joparisot/j8ourfa1/31/

我的HTML:

<div id="app">
    <autocomplete v-model="selection"></autocomplete>
</div>

<template id="autocomplete">
  <div>
    <h2>gernerogrnio</h2>
    <input id="my-input" 
           class="form-control" 
           type="text" 
           :value="value"
           @keydown.enter="updateValue($event.target.value)">
    <p>{{ value }}</p>
  </div>
</template>
Run Code Online (Sandbox Code Playgroud)

我的脚本:

    Vue.component('autocomplete', {
    template: '#autocomplete', 
  props: {
    value: {
      type: String,
      required: true
    }
  }, 
  methods: {
    updateValue (value) {
        var new_value = ''
      if (value.length < 4) {
        new_value = 'Inferior'
      } else {
        new_value = 'Superior'
      }

      this.$emit('input', new_value)
      var myInput = document.getElementById('my-input');
      this.setCaretPosition(myInput, 5)
    }, 
    setCaretPosition(ctrl, pos) {
        ctrl.focus();
        ctrl.setSelectionRange(pos, pos);
    }
  }
});

new Vue({
    el: '#app', 
  data: {
    selection: 'test'
  }
});
Run Code Online (Sandbox Code Playgroud)

我不关心自动完成,但根据您输入的内容,当您按 Enter 时,输入将填充新值。您可以看到,如果注释第 11 至 16 行并将 new_value 设置为 value,则设置光标位置将起作用。

我似乎无法同时做这两件事。有什么想法吗?

Jon*_*sot 5

感谢 Roy J 的评论,我找到了解决方案。

在 updateValue 函数中添加以下内容:

this.$nextTick(() => {
  this.setCaretPosition(myInput, 5)
});
Run Code Online (Sandbox Code Playgroud)