vuejs项目实现 登录界面记住密码自动登录功能+点击回车键登录

分析:

登录时。判断用户是否勾选了自动登录?如果是的话,登录成功后保存用户信息到缓存。下次访问的时候。直接去cookie里面判断有没有就行了。我设置了base64编码和解码

效果:

 

代码:

<template>
  <!-- 登录页 -->
  <!-- 登录板块 -->
  <!-- 注册板块 -->
  <!-- 找回密码板块 -->
  <div class="login-wrap">
    <div class="login-main">
      <el-row type="flex">
        <el-col :span="16" class="login-cont">
          <h3 class="title login-text">
            欢迎使用,<br />xxx平台
          </h3>
          <el-form
            class="extend-mt-20"
            :model="ruleForm"
            ref="ruleForm"
            :rules="rules"
          >
            <el-form-item prop="username">
              <el-input
                type="text"
                v-model="ruleForm.username"
                maxlength="30"
                placeholder="请输入账号"
                :clearable="true"
              ></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                type="password"
                v-model="ruleForm.password"
                placeholder="请输入密码"
                :clearable="true"
                maxlength="30"
                :show-password="true"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-row>
                <el-col :span="12">
                  <el-checkbox v-model="ruleForm.autoLogin"
                  >记住密码
                  </el-checkbox
                  >
                </el-col>
                <el-col :span="12" align="right">
                  <!--                  <span-->
                  <!--                    class="info-item index-text"-->
                  <!--                    @click="handleChangeAction('rpwd')"-->
                  <!--                  >忘记密码?</span-->
                  <!--                  >-->
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item>
              <el-row>
                <el-col :span="12">
                  <el-button
                    type="primary"
                    class="extend-wdb100"
                    @click="handleAction(action)"
                  >{{
                      action == 'login'
                        ? '立即登录'
                        : action == 'reg'
                          ? '注册'
                          : '提交'
                    }}
                  </el-button
                  >
                </el-col>
                <el-col :span="12" align="right">
                  <span
                    v-if="action == 'login'"
                    class="info-item"
                    @click="handleRegister('reg')"
                  >没有账号?去<span class="index-text-reg">注册</span>
                  </span>
                  <span
                    v-if="action == 'reg'"
                    class="info-item"
                    @click="handleChangeAction('login')"
                  >已有账号,现在登录</span
                  >
                  <span
                    v-if="action == 'rpwd'"
                    class="info-item"
                    @click="handleChangeAction('login')"
                  >返回登录</span
                  >
                </el-col>
              </el-row>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="8" class="login-info">
          <h2 class="title">xx</h2>
          <div class="subtitle">xxx项目</div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'

export default {
  name: 'login',
  data() {
    return {
      action: 'login', // 当前行为: login:登录 reg:注册 rpwd:找回密码
      ruleForm: {
        username: null, // 用户名
        password: null, // 密码
        password2: null, // 重复密码
        autoLogin: true, // 是否自动登录
        checkcode: null, // 短信验证码
        agreed: null // 同意用户协议
      }, // 用户登录信息
      rules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' }
        ],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        checkcode: [
          { required: true, message: '请输入短信验证码', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 点击回车键登录
    keyDown(e) {
      // 回车则执行登录方法 enter键的ASCII是13
      if (e.keyCode === 13) {
        this.handleAction('login'); // 定义的登录方法
      }
    },
    /**
     * 清空数据
     **/
    clear() {
      this.ruleForm = {
        username: null, // 用户名
        password: null, // 密码
        autoLogin: true, // 是否自动登录
        checkcode: null, // 短信验证码
        agreed: null // 同意用户协议
      }
      // 清空表单检查结果
      this.$refs.ruleForm.clearValidate()
    },
    /**
     * 改变行为
     * @param action {String} 改变后的行为
     **/
    handleChangeAction(action) {
      // 设置改变后的行为
      this.action = action
      // 清空原有数据
      this.clear()
    },
    handleRegister(action) {
      // 设置改变后的行为
      this.action = action
      // 清空原有数据
      this.clear()
      this.$router.push('/setting')
    },
    /**
     * 按钮动作
     * @param action {String} 行为
     **/
    handleAction(action) {
      // 验证
      this.$refs['ruleForm'].validate(valid => {
        if (valid) {
          const axiosParams = {
            username: this.ruleForm.username,
            password: this.ruleForm.password,
            autoLogin: this.ruleForm.autoLogin
          }
          // 编码密码、密码需要base64转码
          axiosParams.password = window.btoa(axiosParams.password)
          if (action == 'login') {
            // 登录
            // ajax提交
            this.$store
              .dispatch('login', axiosParams)
              .then(res => {
                if (this.$store.state.user.userInfo) {
                  // 登陆成功后,设置为已登录
                  this.$store.state.user.loggedIn = true
                  if (this.$store.state.user.userInfo.username == 'admin') {
                    this.$store.state.user.userInfo.type == 1
                  } else {
                    this.$store.state.user.userInfo.type == 0
                  }
                  this.$message.success('登录成功!')
                  this.$router.push('/index')
                  // 如果用户已登录,则获取用户信息
                  if (getToken()) {
                    this.$store.dispatch('getUserInfo').then(res=>{
                      console.log(res)
                    })

                  }

                } else {
                  this.$message.error('登录失败!')
                }
              })
              .catch(() => {
              })

          } else if (action == 'reg') {
            // 注册
            // 首次访问需要设置管理员账号
            this.$router.push('/setting')
          } else if (action == 'rpwd') {
            // 找回密码
            // // 编码密码、密码需要base64转码
            // axiosParams.password = window.btoa(axiosParams.password)
            this.$api
              .editUserById(axiosParams)
              .then(res => {
                //console.log('找回密码结果', res)
                if (res.data.code == 200) {

                  //this.$message.success('找回密码成功!可以登录了!')
                  this.action = 'login'
                } else {
                  //this.$message.error('找回密码失败!')
                }
              })
            //this.$message.success('找回密码成功')
          }
        } else {
          // 检查未通过
          this.$message.error('请检查修改输入框后再登录!')
        }
      })
    },
  },
  created() {
    if (document.cookie.length > 0) {
      var arr = document.cookie.split('; '); //这里显示的格式需要切割一下自己可输出看下
      for (var i = 0; i < arr.length; i++) {
        var arr2 = arr[i].split('='); //再次切割
        //判断查找相对应的值
        if (arr2[0] == 'username') {
          this.ruleForm.username = arr2[1]; //保存到保存数据的地方
        } else if (arr2[0] == 'password') {
          this.ruleForm.password = window.atob(arr2[1])
        }
      }
    }


  },
  mounted() {
    // //console.log('mounted this',this)
    // 绑定监听事件
    window.addEventListener("keydown", this.keyDown);

  },
  destroyed() {
    // 销毁事件
    window.removeEventListener("keydown", this.keyDown, false);
  },
}
</script>

<style scoped>
.login-wrap {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
}

.login-main {
  width: 600px;
  margin: 0 auto;
  background: #fff;
}

.login-cont {
  padding: 20px;
  border: rgb(64, 144, 246) 1px solid;
}

.login-info {
  background: rgb(107, 129, 199);
  color: #fff;
  text-align: center;
  padding-top: 100px;
}

.login-text-reg {
  color: rgb(107, 129, 199);
  text-decoration: underline;
}

.login-text {
  color: rgb(107, 129, 199);
}

span {
  cursor: pointer;
}



</style>

我们是在vuex里登录的:

// vuex store 用户模块
import api from '@/api'
import { setToken, removeToken } from '@/utils/auth'

// 用户模块
const user = {
  // 状态
  state: {
    userInfo: {}, // 用户信息//
    // loggedIn: false, // 用户是否已登录
    autoLogin: false // 设置自动登录
  },
  // 计算属性
  getters: {},
  // 注册同步方法,调用时使用commit(方法名,参数)
  mutations: {
    // form表单双向绑定
    // 设置用户信息
    SET_USER_INFO(state, payload) {
      state.userInfo = JSON.parse(JSON.stringify(payload))
    },
    // 清除用户信息
    CLEAR_USER_INFO(state) {
      state.userInfo = {}
    },
    // 设置用户自动登录
    SET_AUTO_LOGIN(state, payload) {
      state.autoLogin = payload
    }
  },
  // 注册异步方法,调用时使用dispatch方法
  actions: {
    // 用户名登录
    login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        api
          .login(userInfo)
          .then(data => {
            if (data.data.code==200){
              this._vm.$message.success(data.data.msg)
            }else {
              this._vm.$message.error(data.data.msg)
            }
            console.log(data)
            console.log(data.data.data.token)
            // 设置是否自动登录
            commit('SET_AUTO_LOGIN', userInfo.autoLogin || false)
            console.log('SET_AUTO_LOGIN', userInfo.autoLogin)
            // 设置用户信息
            commit('SET_USER_INFO', data.data.data)
            // 设置token
            setToken(data.data.data.token)
            // 判断用户是否勾选记住密码,如果勾选,向cookie中储存登录信息,
            // 如果没有勾选,储存的信息为空
            if(userInfo.autoLogin){
              let exDays = 30; //过期时间
              let exDate = new Date(); //获取时间
              exDate.setTime(exDate.getTime() + 24 * 60 * 60 * 1000 * exDays); //保存的天数
              //字符串拼接cookie
              window.document.cookie = "username" + "=" + userInfo.username + ";path=/;expires=" + exDate.toGMTString();
              window.document.cookie = "password" + "=" + userInfo.password + ";path=/;expires=" + exDate.toGMTString();
            }else {
              let exDays = -1; //过期时间
              let exDate = new Date(); //获取时间
              exDate.setTime(exDate.getTime() + 24 * 60 * 60 * 1000 * exDays); //保存的天数
              //字符串拼接cookie
              window.document.cookie = "username" + "=" + "" + ";path=/;expires=" + exDate.toGMTString();
              window.document.cookie = "password" + "=" + "" + ";path=/;expires=" + exDate.toGMTString();
            }

            resolve()
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    // 获取用户信息
    getUserInfo({ commit }) {
      return new Promise((resolve, reject) => {
        api
          .getUserInfo()
          .then(data => {
            //console.log('获取当前登录用户信息??', data)
            //console.log('SET_USER_INFO', data.data.data)
            if (!data) {
              reject(new Error('无信息返回'))
            }
            commit('SET_USER_INFO', data.data.data)
            resolve(data)
          })
          .catch(error => {
            // 清除旧的token
            removeToken()
            reject(error)
          })
      })
    },
    // 登出
    logout({ commit }) {
      return new Promise((resolve, reject) => {
        api
          .logout()
          .then(() => {
            removeToken()
            resolve()
          })
          .catch(error => {
            reject(error)
          })
      })
    }

  }
}

export default user

大功告成!

  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

南北极之间

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值