【问题标题】:Losing autofus on Vue.js toggle of v-show在 v-show 的 Vue.js 切换上丢失 autofus
【发布时间】:2016-04-21 14:58:22
【问题描述】:

奇怪,当我更改正在显示的元素时,我的输入的自动对焦属性不起作用

见附上的小提琴:https://jsfiddle.net/e53Lgnnb/6/

代码: HTML:

<body>
<!-- Email [POST] -->
<div class="" id="email" v-show="activeStep == 'email'">
    <form action="onboarding-5.html" @submit.prevent="submitForm('email', 'password')">
        <div class="form-row">
            <input type="email" autofocus required placeholder="email">
        </div>
        <p>
            <button type="submit" class="button">Ok <i class="icon arrow-right"></i></button>
        </p>
    </form>
</div>

<!-- Password [POST] -->
<div class="onboarding-content-wrap" id="password" v-show="activeStep == 'password'">
    <form action="onboarding-6.html">
        <div class="form-row">
            <input type="password" autofocus required placeholder="password">
        </div>
        <p>
            <button type="submit" class="button">Ok <i class="icon arrow-right"></i></button>
        </p>
    </form>
</div>
</body>

JS:

    new Vue({
    el: 'body',

    data: {
        activeStep: 'email',
    },

    methods: {

        // Show the step as active
        getNextStep: function (nextStep) {
            this.activeStep = nextStep;
        },

        submitForm: function (currentStep, nextStep) {
            this.getNextStep(nextStep);
            console.log(response.data);
        }
    }
});

发生了什么事? 非常感谢 !

【问题讨论】:

  • 如果 'autofocus' 标签只被处理一次——当初始 DOM 被加载时,我不会感到惊讶。因此,使用 watch 的解决方案(见下面的答案)似乎非常合理

标签: javascript html laravel vue.js


【解决方案1】:

临时解决,直到我完全理解它为什么不能工作。添加:

watch: {
        activeStep: function () {
          $("#" + this.activeStep + " input[name=" + this.activeStep + "]").focus();
        }
    }

【讨论】:

    【解决方案2】:

    如果您将密码字段设为v-if 而不是v-show 会怎样?提交表单时,您将始终处于密码步骤,因此您不必担心提交时该字段不存在。因为v-if 仅在其为 true 时创建 dom 元素,所以 autofocus 属性将在创建时触发。

    【讨论】:

    • 所以我尝试了,但由于某种原因它让我失去了数据欧芹验证......
    【解决方案3】:

    自动对焦仅适用于page load。如果你想在用户提交表单时改变焦点,我建议你为“activeStep”创建一个手表。

    类似的东西

    watch:{
        activeStep(step){
            if( step === 'email'){
                this.$els.emailField.focus();
            }
            // ...
        }
    },
    

    更多信息:

    自动对焦内容属性允许作者指出 控件将在页面加载后立即聚焦,从而允许 用户只需开始输入,而无需手动聚焦主要 控制。

    不能有两个元素具有相同的最近祖先 都具有 autofocus 属性的 autofocus 作用域根元素 指定。

    https://www.w3.org/TR/html5/forms.html#attr-fe-autofocus

    【讨论】:

      【解决方案4】:

      检查这个 jsfiddle

      jsfiddle.net/blogui91/e53Lgnnb/12/

      我只是创建了一个显示输入的新组件,但随着创建时间的不同,它会根据道具“自动对焦”自动对焦,如果需要的话。和一个名为“模型”的道具,它将帮助您使用“.sync”更新父组件中的值来更新它,希望对您有所帮助

      【讨论】:

      • 我喜欢这样。我将其剥离为 $('input').focus() 准备就绪,因为每个屏幕只有一个 :-)
      猜你喜欢
      • 2017-02-08
      • 2018-07-12
      • 1970-01-01
      • 2020-02-18
      • 1970-01-01
      • 2018-12-31
      • 1970-01-01
      • 2021-11-27
      • 2019-11-30
      相关资源
      最近更新 更多