输入事件时,输入光标跳至输入字段的末尾

Tej*_*a D 5 html javascript vue.js

我正在尝试在输入事件时将用户输入转换为大写

因此,每当我在输入字段中键入键时,都会遇到以下问题

  1. 当用户在中间输入时,光标跳到输入值的末尾。
  2. 最后键入的字符(不是最后一个字符)不会转换为大写。

Here is the link to JS fiddle https://jsfiddle.net/aeL051od/ to reproduce the issue

new Vue({
  el: "#app",
  data() {
    return {
      input: null
    }
  },
  methods: {
    handleInput(e) {
      this.input = e.target.value ?
        e.target.value.toString().toUpperCase() :
        e.target.value;
    }
  }
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <input type="text" v-model="input" @input="handleInput"> {{ input }}
  <!-- {{ input }} is just for reference -->
</div>
Run Code Online (Sandbox Code Playgroud)

Roy*_*y J 6

如果您(或 Vue)将新值复制到输入中,则光标将设置到输入的末尾。如果您想保留之前的位置,则需要捕获该位置,进行更改,然后恢复$nextTick该位置。

另请注意,如果您要this.input在处理程序中进行设置,那么您的 using 也没有意义v-model。保存 也不太可能event是明智的,但你可以。

new Vue({
  el: "#app",
  data() {
    return {
      input: null,
      event: null
    }
  },
  methods: {
    handleInput(e) {
      const el = e.target;
      const sel = el.selectionStart;
      const upperValue = el.value.toUpperCase();

      el.value = this.input = upperValue;
      this.event = e;
      this.$nextTick(() => {
        el.setSelectionRange(sel, sel);
      });
    }
  }
});
Run Code Online (Sandbox Code Playgroud)
#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

input {
  margin-bottom: 20px;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <input type="text" @input="handleInput">
  <p>{{ event ? event.target.value : null }}</p>
  <p>
    {{input}}
  </p>
</div>
Run Code Online (Sandbox Code Playgroud)