1、示例:
2、代码:
只看核心代码块 其他不用管
<template>
<view class="page">
<view class="top-background-raduis"> </view>
<view class="login-box">
<view class="login-card-title">
<view class="login-card-title-content"> 账号密码登录 </view>
</view>
<view class="login-card-input">
<!-- 输入框头部图标 -->
<uni-easyinput class="hj-input" v-model="user.userName" focus maxlength="30" :trim="true"
placeholder="请输入账号"></uni-easyinput>
<!-- 输入框头部图标 -->
<uni-easyinput class="hj-input" v-model="user.password" type="password"
placeholder="请输入密码"></uni-easyinput>
</view>
<!-- 记住密码功能 -->
<view class="remember-psw">
<checkbox-group>
<checkbox type="checkbox" :checked='rememberPsw' @click="rememberPsw = !rememberPsw" color="#09CC86"/>
记住账号密码
</checkbox-group>
</view>
<view class="login-card-loginIn">
<view class="login-card-loginIn-btn" @click="login">
登录
</view>
</view>
</view>
<view class="bottom-message">
版权所有 示例
</view>
</view>
</template>
import {
login
} from "@/pages/login/api/api.js";
export default {
data() {
return {
rememberPsw: true,//复选框状态 默认勾选
user: {
userName: '',//账号
password: ''//密码
}
};
},
mounted() {
//取出缓存中的账号、密码
const HBusername = uni.getStorageSync('HBusername');
const HBpassword = uni.getStorageSync('HBpassword');
console.log("缓存的账号:",HBusername)
console.log("缓存的密码:",HBpassword)
//有账号、密码就赋值给文本,没有就清空
if (HBusername && HBpassword) {
this.user.userName = HBusername;
this.user.password = HBpassword;
}
},
methods: {
//登录
login() {
if (this.auth()) {
login(this.user).then(res => {
if (res.code == '200') {
//勾选就缓存账号、密码
if (this.rememberPsw) {
uni.setStorageSync('HBusername', this.user.userName);
uni.setStorageSync('HBpassword', this.user.password);
} else {//销毁缓存中的账号、密码
uni.removeStorageSync('HBusername');
uni.removeStorageSync('HBpassword');
}
uni.showToast({icon: 'none',title: '登录成功'});
uni.setStorageSync('Admin-Token', res.token);
setTimeout(() => {
uni.reLaunch({
url: '/pages/cyjy/home', //跳转首页
})
}, 500);
}else {
uni.showToast({icon: 'none',title: '登录失败'});
}
}).catch(err => {
console.log(err)
})
}
},
//校验
auth() {
if (this.user.userName.length < 1 || this.user.userName == '' && this.user.password.length < 1 || this.user.password == '') {
uni.showToast({icon: 'none',title: '请输入用户名与密码'});
return false;
}
if (this.user.userName.length < 1 || this.user.userName == '') {
uni.showToast({icon: 'none',title: '请输入用户名'});
return false;
}
if (this.user.password.length < 1 || this.user.password == '') {
uni.showToast({icon: 'none',title: '请输入密码'});
return false;
}
return true;
},
},
}
3、步骤逻辑:
第一次登录输入账号密码默认是勾选记住账号密码的,登录会将账号密码存入进缓存。(复选框做了缓存的存入与销毁,勾选就将账号密码存入缓存,不勾选就销毁缓存。)
账号 key:HBusername
密码 key:HBpassword
第二次及往后每次登录,都会先从缓存中获取账号密码key,将账号密码填充进文本框,没有就不填充。