實現回車鍵自動登錄功能:Vue 2 和 Vue 3 的解決方案 🚀

在開發登錄表單時,提升用户體驗的一個重要功能是:用户輸入完用户名和密碼後,按下回車鍵即可自動觸發登錄。這個功能看似簡單,但在 Vue 2 和 Vue 3 中的實現方式略有不同。本文將詳細介紹如何在 Vue 2 和 Vue 3 中實現這一功能,並提供完整的代碼示例。


效果展示: 請添加圖片描述


功能需求

我們需要實現以下功能:

  1. 在表單中監聽鍵盤事件,當用户按下回車鍵時,自動觸發登錄功能。
  2. 兼容 Vue 2 和 Vue 3 的語法。

Vue 2 的實現方法

在 Vue 2 中,我們可以使用 .native 修飾符來監聽原生 DOM 事件。以下是具體實現步驟:

1. 修改表單元素

<el-form> 標籤上添加 @keydown.enter.native 事件監聽器,監聽回車鍵事件並調用 submitForm 方法。

<el-form ref="formEl" :model="ruleForm" status-icon :rules="rules" label-width="auto" class="demo-ruleForm"
         label-position="top" @keydown.enter.native="submitForm">
  <el-form-item prop="loginName" label="賬號">
    <el-input v-model="ruleForm.loginName" placeholder="username" autocomplete="off" />
  </el-form-item>
  <el-form-item prop="loginSecret" label="密碼">
    <el-input v-model="ruleForm.loginSecret" placeholder="password" type="password" autocomplete="off" />
  </el-form-item>
  <el-form-item class="login-btn">
    <el-button type="primary" @click="submitForm">
      登 錄
    </el-button>
  </el-form-item>
</el-form>

2. 提交表單的方法

methods 中定義 submitForm 方法,用於處理表單提交邏輯。

methods: {
  submitForm() {
    this.$refs.formEl.validate((valid) => {
      if (valid) {
        // 調用登錄接口
        authLogin(this.ruleForm)
          .then(res => {
            // 處理登錄成功邏輯
          })
          .catch(err => {
            // 處理登錄失敗邏輯
          });
      } else {
        console.log('表單驗證失敗!');
      }
    });
  }
}

Vue 3 的實現方法

在 Vue 3 中,.native 修飾符已被棄用,因為 Vue 3 的事件機制更加智能,默認會將原生事件綁定到組件的根元素上。以下是具體實現步驟:

1. 修改表單元素

直接使用 @keydown.enter 監聽回車鍵事件,無需 .native 修飾符。

<el-form ref="formEl" :model="ruleForm" status-icon :rules="rules" label-width="auto" class="demo-ruleForm"
         label-position="top" @keydown.enter="submitForm">
  <el-form-item prop="loginName" label="賬號">
    <el-input v-model="ruleForm.loginName" placeholder="username" autocomplete="off" />
  </el-form-item>
  <el-form-item prop="loginSecret" label="密碼">
    <el-input v-model="ruleForm.loginSecret" placeholder="password" type="password" autocomplete="off" />
  </el-form-item>
  <el-form-item class="login-btn">
    <el-button type="primary" @click="submitForm">
      登 錄
    </el-button>
  </el-form-item>
</el-form>

2. 提交表單的方法

與 Vue 2 類似,定義 submitForm 方法處理表單提交邏輯。

methods: {
  submitForm() {
    this.$refs.formEl.validate((valid) => {
      if (valid) {
        // 調用登錄接口
        authLogin(this.ruleForm)
          .then(res => {
            // 處理登錄成功邏輯
          })
          .catch(err => {
            // 處理登錄失敗邏輯
          });
      } else {
        console.log('表單驗證失敗!');
      }
    });
  }
}

如果你有其他問題或更好的實現方式,歡迎在評論區分享!😄

您好,我是肥晨。 歡迎關注我獲取前端學習資源,日常分享技術變革,生存法則;行業內幕,洞察先機。