在 Vue 上失去自动.js v-show 的切换



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

请参阅随附的小提琴: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);
        }
    }
});

这是怎么回事?多谢!

自动对焦仅适用于page load。如果您想在用户提交表单时更改焦点,我建议您为"activeStep"创建一个监视。

像这样的东西

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

更多信息:

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

不得有两个元素具有相同的最近祖先都具有自动对焦属性的自动对焦范围根元素指定。

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

检查这个 jsfiddle

jsfiddle.net/blogui91/e53Lgnnb/12/

我只是创建了一个显示输入的新组件,但是由于创建时间的不同,它会自动聚焦,具体取决于道具"自动对焦",如果需要的话也是如此。 和一个名为"模型"的道具,它将帮助您使用".sync"更新父组件中的值来更新它,希望对您有所帮助

临时工作,直到我确切地理解为什么它不起作用。加:

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

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

最新更新