uniapp登录首页
uniapp 登录首页实现方法
页面结构设计
在 pages 目录下创建登录页面(如 login.vue),使用 uni-app 基础组件构建表单:
<template>
<view class="login-container">
<input type="text" v-model="username" placeholder="请输入用户名"/>
<input type="password" v-model="password" placeholder="请输入密码"/>
<button @click="handleLogin">登录</button>
</view>
</template>
数据绑定与验证
通过 v-model 实现双向数据绑定,添加基础验证逻辑:

export default {
data() {
return {
username: '',
password: ''
}
},
methods: {
handleLogin() {
if (!this.username || !this.password) {
uni.showToast({ title: '请填写完整信息', icon: 'none' });
return;
}
this.submitToServer();
}
}
}
接口请求封装
使用 uni.request 调用后端接口:
methods: {
async submitToServer() {
try {
const res = await uni.request({
url: 'https://your-api.com/login',
method: 'POST',
data: {
username: this.username,
password: this.password
}
});
if (res.data.code === 200) {
this.saveTokenAndRedirect(res.data.token);
}
} catch (e) {
uni.showToast({ title: '登录失败', icon: 'none' });
}
}
}
登录状态管理
成功登录后存储 token 并跳转:

methods: {
saveTokenAndRedirect(token) {
uni.setStorageSync('token', token);
uni.reLaunch({ url: '/pages/home/index' });
}
}
自动登录判断
在 App.vue 的 onLaunch 中检查本地 token:
onLaunch() {
const token = uni.getStorageSync('token');
if (token) {
uni.reLaunch({ url: '/pages/home/index' });
} else {
uni.reLaunch({ url: '/pages/login' });
}
}
样式优化建议
添加基础样式提升用户体验:
.login-container {
padding: 40rpx;
}
input {
border: 1px solid #eee;
margin-bottom: 20rpx;
padding: 20rpx;
}
button {
background-color: #007AFF;
color: white;
}
安全注意事项
- 密码传输需使用 HTTPS 协议
- 敏感信息避免存储在本地缓存
- 建议添加图形验证码或短信验证防止暴力破解
- 服务端应做接口限流和防 SQL 注入处理






