Przeglądaj źródła

feat: 登录页面支持enter

lvkun996 2 lat temu
rodzic
commit
6111004429
2 zmienionych plików z 25 dodań i 5 usunięć
  1. 15 2
      src/directives/index.ts
  2. 10 3
      src/pages/login/index.vue

+ 15 - 2
src/directives/index.ts

@@ -2,13 +2,26 @@ import { message } from 'ant-design-vue'
 import { Directive, onUnmounted, DirectiveBinding } from 'vue'
 
 export const keyboard: Directive = {
-  mounted (el, binding: DirectiveBinding) {
+  mounted (el: HTMLDivElement, binding: DirectiveBinding) {
+    const key = binding.arg
+    console.log('key:', el, binding)
+
     const handleKeyPress = (event) => {
-      if (event.key === 'Enter') {
+      console.log(event)
+
+      if (event.key === key) {
         binding.value() // 执行绑定的方法
       }
     }
 
+    el.addEventListener('keydown', () => {
+      console.log('keydown')
+    })
+
+    el.addEventListener('keyup', () => {
+      console.log('keyup')
+    })
+
     el.addEventListener('keypress', handleKeyPress)
 
     // 在组件卸载时移除事件监听器

+ 10 - 3
src/pages/login/index.vue

@@ -43,16 +43,15 @@
           </a-form>
         </a-col>
         <a-col :span="24" style="display: flex;justify-content: center;">
-          <a-button style="width: 200px;" type="primary" @click="login">登录</a-button>
+          <a-button @click="login" style="width: 200px;" type="primary" >登录</a-button>
         </a-col>
       </a-row>
     </a-col>
   </a-row>
 </template>
 <script lang='ts' setup >
-import { useRoute } from 'vue-router'
 import { useUserStore } from '@/store/index'
-import { reactive } from 'vue'
+import { onUnmounted, reactive } from 'vue'
 import { useStaticImg } from '@/utils/static'
 
 // const { redirct_url } = useRoute().query
@@ -61,6 +60,10 @@ const userStore = useUserStore()
 
 const staticImg = useStaticImg()
 
+window.addEventListener('keypress', event => {
+  if (event.key === 'Enter') login()
+})
+
 const state = reactive({
   userAccount: '',
   password: ''
@@ -70,6 +73,10 @@ const login = () => {
   userStore.login(state)
 }
 
+onUnmounted(() => {
+  window.removeEventListener('keypress', () => {})
+})
+
 </script>
 <style lang='less' scoped >
 .app-name {