Vue中监听键盘事件(该文档记录enter)

按键盘Enter回车,实现用户登录

vue代码(html+js)

下面展示 引用element组件el-input实现用户信息输入并绑定回车事件

// 关键在于
@keyup.enter.native="searchFile"
// An highlighted block
<el-form class="m-login" :model="loginForm" ref="loginForm">
    <el-form-item prop="account" :rules="[
      { required: true, message: '请输入账号', trigger: 'blur' }]">
      <el-input class="item" v-model="loginForm.account" placeholder="账号" @keyup.enter.native="searchFile"></el-input>
      <span class="ypt-icon ypt-icon-account"></span>
    </el-form-item>
    <el-form-item prop="password" :rules="[
      { required: true, message: '请输入密码', trigger: 'blur' }]">
      <el-input class="item" type="password" v-model="loginForm.password" placeholder="密码" @keyup.enter.native="searchFile"></el-input>
      <span class="ypt-icon ypt-icon-password"></span>
    </el-form-item>
    <el-form-item>
      <el-checkbox v-model="checked">记住我</el-checkbox>
    </el-form-item>
    <el-form-item>
      <el-button class="btn" type="primary" @click="onSubmit()">登录</el-button>
    </el-form-item>
</el-form>

下面展示 methods下面的函数实现

// An highlighted block
	searchFile(e){
          let _this = this;
          _this.onSubmit();
     }

备注说明:

在Vue中,已经为常用的按键设置了别名,这样我们就无需再去匹配keyCode,直接使用别名就能监听按键的事件。
例如:

// 下面三句代码等价
<input v-on:keyup.13="submit">
<input @keyup.enter="submit">
<input v-on:keyup.enter="submit">

注意!!!如果用了封装组件的话,比如element,这个时候使用按键修饰符需要加上.native

// 实现如下:
<el-input class="item" v-model="loginForm.account" @keyup.enter.native="searchFile"></el-input>

如果遇到.native修饰符也无效的情况,可能就需要用到$listeners了,具体用法请参考Vue官方文档:将原生事件绑定到组件。 https://cn.vuejs.org/v2/guide/components-custom-events.html#将原生事件绑定到组件

猜你喜欢

转载自blog.csdn.net/qq_29954811/article/details/87937561
今日推荐