Files
kangyuan-mobile/pages/public/login.vue
T

708 lines
20 KiB
Vue

<template>
<!-- 空登陆页 -->
<s-layout navbar="inner" title="登录" navPreset="float">
<view class="login" @tap="onPageTap">
<view class="login_top_img w100" :style="{ top: -height + 'px' }">
<image src="@/static/index/login_bg.png" mode="widthFix" class="w100" />
</view>
<view class="login_con w100 flex-column ju-between">
<view class="login_top">
<view class="font-Heavy size52 c1">Hello!</view>
<view class="font-Heavy size52 c1">欢迎使用优购商城</view>
</view>
<view class="bottomCon">
<view class="login_bottom">
<view class="size40 f500 title">{{ dataObj.con[type].title }}</view>
<view class="form">
<uni-forms ref="form" label-position="top">
<view v-for="(v, i) in dataObj.con[type].arr" :key="i">
<uni-forms-item
:required="dataObj.formArr[v].required !== false"
:label="dataObj.formArr[v].title"
:name="dataObj.formArr[v].value"
>
<view class="flex-center border_bottom login-input-wrap" @tap.stop>
<image class="input-icon" :src="inputIconMap[v]" mode="aspectFit" />
<uni-easyinput
v-model="formData[dataObj.formArr[v].value]"
:placeholder="dataObj.formArr[v].placeholder"
:type="dataObj.formArr[v].type"
:inputBorder="false"
:maxlength="dataObj.formArr[v].max"
:disabled="dataObj.formArr[v].value === 'inviteCode'"
@focus="() => onInputFocus(dataObj.formArr[v].value)"
@input="() => onInputInput(dataObj.formArr[v].value)"
/>
<view v-if="v == 2" class="c_code size28" @click="getCode">{{
num > 0 && num < 60 ? num + 's后重新获取' : '获取验证码'
}}</view>
<view v-if="v == 6" class="invite-scan-icon _icon-scan" @tap.stop="onInviteScan"></view>
<view
v-if="shouldShowDropdownIcon(dataObj.formArr[v].value)"
class="login-suggest-icon"
@tap.stop="() => onToggleDropdown(dataObj.formArr[v].value)"
>
<uni-icons type="bottom" size="18" color="#C6C6C6" />
</view>
</view>
<scroll-view
v-if="shouldShowSuggestionList(dataObj.formArr[v].value)"
class="login-suggest"
scroll-y="true"
:show-scrollbar="false"
enhanced
@tap.stop
@touchmove.stop
>
<view
v-for="item in suggestionListFor(dataObj.formArr[v].value)"
:key="item.mobile"
class="login-suggest-item"
@tap.stop="() => onSelectSuggestion(item)"
>
<template v-if="dataObj.formArr[v].value === 'password'">
<view class="login-suggest-title">{{ formatPasswordPreview(item.password) }}</view>
<view class="login-suggest-sub">{{ item.mobile }}</view>
</template>
<template v-else>
<view class="login-suggest-title">{{ item.mobile }}</view>
<view class="login-suggest-sub">{{ item.hasPassword ? '已保存密码' : '仅保存账号' }}</view>
</template>
</view>
</scroll-view>
</uni-forms-item>
</view>
</uni-forms>
</view>
<view class="flex-row ju-between size28 btns">
<view class="flex-row">
<view class="">{{ dataObj.con[type].text }}</view>
<view
class="c_switch"
@click="typeChange(dataObj.btns[dataObj.con[type].btn1].value)"
>{{ dataObj.btns[dataObj.con[type].btn1].text }}</view
>
</view>
<view
class="c_switch"
@click="typeChange(dataObj.btns[dataObj.con[type].btn2].value)"
v-if="dataObj.con[type].btn2"
>{{ dataObj.btns[dataObj.con[type].btn2]?.text }}</view
>
</view>
<view class="submit-btn" :class="{ 'submit-btn--disabled': submitLoading }" @tap="handleSubmit">
{{ dataObj.con[type].sub }}
</view>
</view>
<view class="radio-box">
<radio-group @change="radioChange">
<label class="flex-center">
<radio color="#C02F3B" class="radio" value="1" :checked="false" />
<view class="flex-center size24">
我已阅读并同意
<text class="c_agreement" @click="go(2)">《用户服务协议》</text>
和
<text class="c_agreement" @click="go(1)">《隐私政策》</text>
</view>
</label>
</radio-group>
</view>
</view>
</view>
</view>
</s-layout>
</template>
<script setup>
import { ref, reactive, computed, nextTick } from 'vue';
import sheep from '@/sheep';
import { onLoad } from '@dcloudio/uni-app';
import AuthUtil from '@/sheep/api/member/auth';
import { scanInviteCode } from '@/utils/qrScanner';
let type = ref(2);
let formData = reactive({
mobile: '',
code: '',
password: '',
confirmPassword: '',
inviteCode: '',
});
let num = ref(0);
const inputIconMap = {
1: '/static/icon/icon1.png',
2: '/static/icon/icon2.png',
3: '/static/icon/icon3.png',
4: '/static/icon/icon3.png',
5: '/static/icon/icon4.png',
6: '/static/icon/icon5.png',
};
let dataObj = reactive({
con: {
1: {
title: '验证码登录',
arr: [1, 2],
text: '还没账号?',
btn1: 1,
btn2: 2,
sub: '立即登录',
toast: '登录成功',
},
2: {
title: '密码登录',
arr: [1, 3],
text: '还没账号?',
btn1: 1,
btn2: 3,
sub: '立即登录',
toast: '登录成功',
},
3: {
title: '用户注册',
arr: [1, 2, 4, 5, 6],
text: '已有账号,',
btn1: 4,
btn2: 3,
sub: '立即注册',
toast: '注册成功',
},
4: {
title: '忘记密码',
arr: [1, 2, 4, 5],
text: '已有账号,',
btn1: 4,
btn2: 2,
sub: '修改密码',
toast: '修改成功',
},
},
formArr: {
1: {
title: '手机号',
type: 'number',
value: 'mobile',
max: 11,
placeholder: '请输入手机号',
},
2: {
title: '验证码',
type: 'number',
value: 'code',
max: 4,
placeholder: '请输入验证码',
},
3: {
title: '密码',
type: 'password',
value: 'password',
placeholder: '请输入密码',
},
4: {
title: '设置密码',
type: 'password',
value: 'password',
placeholder: '请输入您的密码',
},
5: {
title: '确认密码',
type: 'password',
value: 'confirmPassword',
placeholder: '请再次输入您的密码',
},
6: {
title: '邀请码',
type: 'text',
value: 'inviteCode',
max: 32,
placeholder: '请扫码获取邀请码',
},
},
btns: {
1: {
text: '去注册',
value: 3,
},
2: {
text: '密码登录',
value: 2,
},
3: {
text: '验证码登录',
value: 1,
},
4: {
text: '去登录',
value: 2,
},
},
});
const rules = reactive({
mobile: [
{
required: true,
message: '请输入手机号',
trigger: 'blur',
},
{
pattern: /^1[3456789]\d{8}$/,
message: '手机号格式不正确',
trigger: 'blur',
},
],
code: [
{
required: true,
message: '请输入验证码',
trigger: 'blur',
},
],
password: [
{
required: true,
message: '请输入密码',
trigger: 'blur',
},
],
});
const typeChange = (val) => {
console.log(val);
type.value = val;
clearInterval(timer.value);
num.value = 0;
};
const radioValue = ref();
const radioChange = (e) => {
radioValue.value = e.detail.value;
};
const LOGIN_HISTORY_KEY = 'login-history';
const HISTORY_LIMIT = 20;
const loginHistory = ref([]);
const dropdownVisibleFor = ref('');
const submitLoading = ref(false);
const hasAnyHistory = computed(() => {
const list = Array.isArray(loginHistory.value) ? loginHistory.value : [];
return list.length > 0;
});
const canUseLoginHistory = computed(() => {
const arr = dataObj?.con?.[type.value]?.arr;
return Array.isArray(arr) && arr.includes(3);
});
const mobileQuery = computed(() => String(formData.mobile || '').trim());
const filteredHistory = computed(() => {
const query = mobileQuery.value;
const list = Array.isArray(loginHistory.value) ? loginHistory.value : [];
const normalized = list
.filter((item) => item && item.mobile)
.map((item) => ({
mobile: String(item.mobile),
password: item.password ? String(item.password) : '',
updatedAt: Number(item.updatedAt || 0),
hasPassword: Boolean(item.password),
}))
.sort((a, b) => b.updatedAt - a.updatedAt);
if (!query) return normalized;
return normalized.filter((item) => item.mobile.includes(query));
});
const passwordHistory = computed(() => filteredHistory.value.filter((item) => item.hasPassword));
function loadLoginHistory() {
try {
const raw = uni.getStorageSync(LOGIN_HISTORY_KEY);
const parsed = raw ? JSON.parse(raw) : [];
loginHistory.value = Array.isArray(parsed) ? parsed : [];
} catch (e) {
loginHistory.value = [];
}
}
function persistLoginHistory() {
try {
uni.setStorageSync(LOGIN_HISTORY_KEY, JSON.stringify(loginHistory.value.slice(0, HISTORY_LIMIT)));
} catch (e) {}
}
function upsertLoginHistory({ mobile, password }) {
const nextMobile = String(mobile || '').trim();
if (!/^1\d{10}$/.test(nextMobile)) return;
const nextPassword = String(password || '');
const now = Date.now();
const next = Array.isArray(loginHistory.value) ? [...loginHistory.value] : [];
const existingIndex = next.findIndex((item) => String(item?.mobile || '') === nextMobile);
const payload = { mobile: nextMobile, password: nextPassword, updatedAt: now };
if (existingIndex >= 0) next.splice(existingIndex, 1, payload);
else next.unshift(payload);
loginHistory.value = next.sort((a, b) => Number(b.updatedAt || 0) - Number(a.updatedAt || 0));
persistLoginHistory();
}
function onPageTap() {
dropdownVisibleFor.value = '';
}
function onToggleDropdown(field) {
if (!canUseLoginHistory.value) return;
const next = dropdownVisibleFor.value === field ? '' : field;
if (next && !suggestionListFor(field).length) return;
dropdownVisibleFor.value = next;
}
function onInputFocus(field) {
if (!canUseLoginHistory.value) return;
if (field !== 'mobile' && field !== 'password') return;
if (!suggestionListFor(field).length) return;
dropdownVisibleFor.value = field;
}
function onInputInput(field) {
if (!canUseLoginHistory.value) return;
if (field !== 'mobile') return;
if (!filteredHistory.value.length) {
dropdownVisibleFor.value = '';
return;
}
if (dropdownVisibleFor.value !== 'mobile') dropdownVisibleFor.value = 'mobile';
}
function shouldShowDropdownIcon(field) {
if (!canUseLoginHistory.value) return false;
if (!hasAnyHistory.value) return false;
return field === 'mobile' || field === 'password';
}
function shouldShowSuggestionList(field) {
if (!canUseLoginHistory.value) return false;
if (dropdownVisibleFor.value !== field) return false;
return suggestionListFor(field).length > 0;
}
function suggestionListFor(field) {
if (field === 'password') return passwordHistory.value;
return filteredHistory.value;
}
function onSelectSuggestion(item) {
formData.mobile = item.mobile;
if (item.hasPassword) formData.password = item.password;
dropdownVisibleFor.value = '';
nextTick(() => {
uni.hideKeyboard();
});
}
function formatPasswordPreview(value) {
const text = String(value || '');
if (!text) return '******';
const len = Math.min(Math.max(text.length, 6), 12);
return '•'.repeat(len);
}
const sub = async () => {
if (!radioValue.value) {
uni.showToast({
title: '请阅读服务协议和隐私协议',
duration: 1000,
icon: 'none',
});
return;
}
let arr = dataObj.con[type.value].arr;
let obj = {};
for (let i = 0; i < arr.length; i++) {
const formItem = dataObj.formArr[arr[i]];
const valueKey = formItem?.value;
const required = formItem?.required !== false;
const value = formData[valueKey];
if (required && !value) {
uni.showToast({
title: formItem?.placeholder,
icon: 'none',
});
return;
}
if (value || required) obj[valueKey] = value;
}
let url = '';
switch (type.value) {
case 1: //密码登录
url = AuthUtil.smsLogin;
break;
case 2: //验证码登录
url = AuthUtil.login;
break;
case 3: //注册
if (obj.password != obj.confirmPassword) {
uni.showToast({
title: '两次密码不一致',
icon: 'none',
});
return;
}
url = AuthUtil.register;
break;
case 4: //忘记密码
break;
}
if (!url) return;
const res = await url(obj).catch(() => null);
if (res?.code === 0) {
if (type.value == 3) {
typeChange(2);
return;
}
if (type.value === 2) {
upsertLoginHistory({ mobile: formData.mobile, password: formData.password });
}
sheep.$store('user').getInfo();
setTimeout(() => {
uni.reLaunch({ url: '/pages/index/index' });
}, 1000);
}
};
const handleSubmit = async () => {
if (submitLoading.value) return;
submitLoading.value = true;
dropdownVisibleFor.value = '';
uni.hideKeyboard();
await nextTick();
await new Promise((resolve) => setTimeout(resolve, 80));
try {
await sub();
} finally {
setTimeout(() => {
submitLoading.value = false;
}, 300);
}
};
let timer = ref();
const getCode = () => {
if (num.value > 0 && num.value < 60) {
return;
}
if (!radioValue.value) {
uni.showToast({
title: '请阅读服务协议和隐私协议',
duration: 1000,
icon: 'none',
});
return;
}
// 发送验证码
if (!formData.mobile) {
uni.showToast({
title: '请输入手机号',
icon: 'none',
});
return;
} else {
sendCode();
}
};
const sendCode = async () => {
let numType = 1;
switch (type.value) {
case 1: //验证码登录1
numType = 1;
break;
case 2: //密码登录1
numType = 1;
break;
case 3: //注册6
numType = 6;
break;
case 4: //忘记密码4
numType = 4;
break;
}
AuthUtil.sendSmsCode({ mobile: formData.mobile, scene: numType }).then((res) => {
if (res.code === 0) {
num.value = 60;
timer.value = setInterval(() => {
num.value--;
if (num.value <= 0) {
clearInterval(timer.value);
num.value = 60;
}
}, 1000);
}
});
};
const go = (type) => {
uni.navigateTo({ url: '/pages/home/agreement?type=' + type });
};
const onInviteScan = async () => {
const code = await scanInviteCode({ toastOnError: true, allowCamera: false });
if (!code) return;
formData.inviteCode = code;
};
onLoad(async () => {
loadLoginHistory();
});
let sysInfo = uni.getSystemInfoSync();
const windowHeight = sysInfo.windowHeight;
let height = ref(0);
height.value = sysInfo.statusBarHeight + uni.upx2px(88);
</script>
<style lang="scss" scoped>
.login {
position: relative;
min-height: 100vh;
padding-bottom: 200rpx;
.login_top_img {
position: absolute;
z-index: 1;
}
.login_con {
position: relative;
height: 100vh;
padding-top: 50rpx;
box-sizing: border-box;
z-index: 1;
// position: absolute;
// top: 166rpx;
// left: 0;
// z-index: 2;
// background-color: #F2F4F7;
}
}
.login_top {
padding-left: 50rpx;
margin-bottom: 48rpx;
}
.bottomCon {
width: 90%;
margin: 0 auto;
background-color: #ffffff;
border-radius: 40rpx;
position: absolute;
top: 220rpx;
left: 5%;
box-sizing: border-box;
overflow: hidden;
padding: 0 0 20rpx;
}
.login_bottom {
// background: linear-gradient(144deg, #19203b 0%, #070c18 100%);
border-radius: 40rpx;
padding: 40rpx;
box-sizing: border-box;
}
.border_bottom {
background-color: #f3f4f7;
border-radius: 10rpx;
padding: 0 24rpx;
box-sizing: border-box;
min-height: 80rpx;
}
.submit-btn {
margin-top: 40rpx;
height: 108rpx;
border-radius: 54rpx;
font-size: 36rpx;
font-weight: 700;
background: linear-gradient(
135deg,
var(--primary-grad-start, #2c8cfa) 0%,
var(--primary-grad-end, #3d5efb) 100%
);
box-shadow: 0 18rpx 44rpx var(--primary-shadow, rgba(47, 124, 246, 0.35));
}
.submit-btn--disabled {
opacity: 0.72;
}
.input-icon {
width: 40rpx;
height: 40rpx;
margin-right: 16rpx;
flex-shrink: 0;
}
.radio-box {
padding-top: 20rpx;
padding-bottom: 36rpx;
// background-color: #ffffff;
}
.radio {
transform: scale(0.6);
}
.btns {
margin-top: 40rpx;
}
.title {
margin-bottom: 30rpx;
}
:deep(.uni-radio-input) {
background-color: transparent;
}
.c_agreement {
color: #c02f3b;
}
.c_switch {
color: #c02f3b;
}
.c_code {
color: #c02f3b;
}
:deep(.border_bottom .uni-easyinput__content) {
border: none !important;
background: transparent !important;
}
.login-input-wrap {
position: relative;
}
.login-suggest-icon {
padding-left: 12rpx;
padding-right: 6rpx;
display: flex;
align-items: center;
}
.invite-scan-icon {
margin-left: auto;
padding-left: 12rpx;
padding-right: 6rpx;
display: flex;
align-items: center;
font-size: 36rpx;
color: #c6c6c6;
}
.login-suggest {
position: absolute;
left: 0;
right: 0;
top: calc(100% + 8rpx);
background: #ffffff;
border-radius: 20rpx;
box-shadow: 0 16rpx 40rpx rgba(0, 0, 0, 0.12);
z-index: 20;
overflow: hidden;
max-height: 420rpx;
}
.login-suggest-item {
padding: 20rpx 24rpx;
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: 2rpx solid rgba(0, 0, 0, 0.06);
box-sizing: border-box;
}
.login-suggest-item:last-child {
border-bottom: none;
}
.login-suggest-title {
font-size: 28rpx;
font-weight: 700;
color: #111111;
}
.login-suggest-sub {
font-size: 22rpx;
color: #9aa0aa;
font-weight: 600;
}
</style>