【问题标题】:Keeping the cursor on the textbox after pressing Enter button按下 Enter 按钮后将光标保持在文本框上
【发布时间】:2021-04-12 20:28:27
【问题描述】:

我想在 VUEJS 方面得到一点帮助。 我有一个表格,我有一个文本框。单击输入按钮时,它会给我一些结果并清除文本框,但闪烁的光标不会回到文本框。 关于如何实现它的任何想法 ->

1. I write some text in the text box
2. Presses Enter 
3. Provides some info and clears the text box
4. Same text box starts to blink and i need to be able to write something back again

这是我的代码:

<template>
  <div class="app-container app-card">
    <div class="app-content">
          <b-form-input-with-validation
            v-model="number"
            :rules="{max: 255, required: true}"
            label="number"
            name="number"
            type="text"
            @keyup.enter="onSubmitClick"
            ref="track"
          />
    </div>
  </div>
</template>
<script>
  export default {

    methods: {
     
      reset() {
        this.innerValue.tracking_number = null
      },

      async onSubmitClick() {
        this.$refs.track.focus()
      },
    },
    data() {
      return {
        track: null,
      }
    },
  }
</script>

我收到此错误:

this.$refs.track.focus is not a function

【问题讨论】:

    标签: javascript vue.js vue-component bootstrap-vue vuejs3


    【解决方案1】:

    在文本框上放置一个template ref,以便您可以通过 clear 方法对其进行聚焦。

    选项 API(使用 &lt;b-form-input&gt;

    <b-form-input v-model="number" ref="refText"></b-form-input>
    
    methods: {
     clear() {
        this.$refs.refText.focus();
      }
    }
    

    组合 API(使用常规 &lt;input&gt;

    <input ref="refText" />
    
    setup() {
      const refText = ref(null);
    }
    
    const clear = function() {
       refText.value.focus();
    }
    

    这是一个演示:

    const { createApp, ref } = Vue;
    const app = createApp({
      setup() {
        const mytext = ref('press button to clear me');
        const refText = ref(null);
        
        const clear = function() {
          mytext.value = '';
          refText.value.focus();
        }
    
        return {
          mytext,
          refText,
          clear
        }
      }
    });
    app.mount("#app");
    <div id="app">
      <input v-model="mytext" ref="refText" />
      <button @click="clear">Clear</button>
    </div>
    
    <script src="https://unpkg.com/vue@next"></script>

    【讨论】:

    • 我已经更新了代码,我收到了一些错误信息。
    • 不适用于自定义组件。这就是为什么您应该始终在问题中显示代码的原因。您没有提及或展示 Bootstrap Vue 或自定义组件,而您正在使用选项 API。
    • 使用普通的&lt;b-form-input&gt; 就可以了
    • 当然,正如您在演示中看到的那样,它确实有效。出于某种原因,您是否需要通过&lt;b-form-input&gt; 看到它?
    • 嗨,@dan 非常感谢您的帮助。此链接:jsfiddle.net/sh0ber/buec0k26 在一定程度上有助于对此进行排序。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-04
    • 2014-05-16
    • 1970-01-01
    • 2019-03-15
    • 1970-01-01
    • 2010-11-13
    • 1970-01-01
    相关资源
    最近更新 更多