3.2 E-commerce background management system supplement --- Enter key login function

When logging in at the front end, there is usually a login button, and you can log in with one click. However, in order to enhance the user experience, you can log in if you press the Enter key, so it will be more convenient to log in.

accomplish

After the basic login steps are completed, the enter key login effect is added, and the enter key login is two steps:

  1. In vue's mounted hook, add button listener events
  2. Then define the event handler function.

insert image description here

 mounted () {
    // 绑定事件
    window.addEventListener('keydown', this.keyDown)
  },
 methods: {
    // 点击重置按钮,重置登录表单
    resetLoginForm () {
      // console.log(this);
      this.$refs.loginFormRef.resetFields()
    },
    // 表单的预验证
    login () {
      const encryptor = new JSEncrypt() // 新建JSEncrypt对象
      this.$refs.loginFormRef.validate(async (valid) => {
        // console.log(valid)
        if (!valid) return

        encryptor.setPublicKey(publicKey) // 设置公钥

        const rsaPassWord = encryptor.encrypt(this.loginForm.password) // 对需要加密的数据进行加密

        this.loginForm.password = rsaPassWord

        const { data: res } = await this.$http.post('login', this.loginForm)
        if (res.meta.status !== 200) return this.$message.error('登录失败')
        this.$message.success('登录成功!')
        // 1. 将登陆成功之后的 token,保存到客户端的 sessionStorage中
        //  1.1 项目中除了登录之外的其他API接口,必须在登录之后才能访问
        //  1.2 token 只应在当前网站打开期间生效,所以将 token 保存到 sessionStorage中
        //  1.3 localStorage 是持久化的存储机制,sessionStorage是会话期间的存储机制
        window.sessionStorage.setItem('token', res.data.token)
        // 2. 通过编程式导航跳转到后台主页,路由地址是 /home
        this.$router.push('/home')
      })
    },
    keyDown (e) {
      // 判断按下是否是回车键
      if (e.keyCode === 13) {
        // 判断用户名密码是否为空
        if (this.loginForm.password === '' || this.loginForm.username === '') { // 如果二者其一为空则不执行任何操作
          return false
        } else { // 如果两个都不为空则执行登录操作
          // 登录方法
          this.login()
        }
      }
    }
  }

Guess you like

Origin blog.csdn.net/weixin_47505105/article/details/123623192