vuejs:尝试使用v-el指令集中输入

Ani*_*ruz 15 vue.js

我正在创建一个向导登录表单,其中首先输入手机号码,然后输入密码.

这里我试图使用密码输入

this.$$.passwordInput.focus()
Run Code Online (Sandbox Code Playgroud)

但是如果我得到下面给出的错误

Uncaught TypeError: Cannot read property 'focus' of undefined
Run Code Online (Sandbox Code Playgroud)

完整代码如下

的index.html

<div id="login">
  <div v-if="flow.mobile">
    <form v-on="submit: checkmobile">
        <p>
          Mobile Number<br>
          <input type="text" v-model="mobile_number" v-el="mobileNumber">
        </p>
    </form>
  </div>
  <div v-if="flow.password">
    <form v-on="submit: checkpassword">
        <p>
          Password<br>
          <input type="password" v-model="password" v-el="passwordInput">
        </p>
    </form>
  </div>
Run Code Online (Sandbox Code Playgroud)

的script.js

var demo = new Vue({
el: '#login',
data: {
    flow: {
        mobile: true,
        password: false
    }
},
methods: {
    checkmobile: function(e) {
        e.preventDefault();
        this.flow.mobile = false;
        this.flow.password = true;
        this.$$.passwordInput.focus();
    },
    checkpassword: function(e) {
        e.preventDefault();
    }
}
Run Code Online (Sandbox Code Playgroud)

});

Eva*_*You 43

您的passwordInput位于v-if块内,只有在设置flow.password为true 时才会呈现; 但是Vue使用异步渲染,因此不会立即渲染v-if块.您可以使用Vue.nextTick它等到它:

this.flow.password = true;
var self = this;
Vue.nextTick(function () {
  self.$$.passwordInput.focus();
});
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请阅读有关异步呈现的指南:http://vuejs.org/guide/best-practices.html#Understanding_Async_Updates


Seb*_*ara 10

如果您使用vuejs 2,您应该阅读:

https://vuejs.org/v2/guide/migration.html#v-el-and-v-ref-replaced

-

在这种情况下,在您的模板中:

使用ref="passwordInput"替代v-el="passwordInput"

在你的方法中:

this.$refs.passwordInput.focus()
Run Code Online (Sandbox Code Playgroud)

希望这对你有所帮助!

  • 我得到:`Uncaught TypeError: Cannot read property 'passwordInput' of undefined` (2认同)

Luk*_*tor 9

在Vue.js 2.x中,您可以创建自己的指令来自动聚焦字段:

Vue.directive('focus', {
    inserted: function (el) {
        el.focus();
    },
    update: function (el) {
        Vue.nextTick(function() {
              el.focus();
        })
    }
})
Run Code Online (Sandbox Code Playgroud)

然后,您可以v-focus在输入和其他元素上使用属性:

<input v-focus>
Run Code Online (Sandbox Code Playgroud)

工作示例:https://jsfiddle.net/LukaszWiktor/cap43pdn/