uniapp登录首页
实现UniApp登录首页的方法
页面结构设计
创建一个login.vue文件作为登录页面,使用<template>定义页面布局。常用组件包括<view>容器、<input>输入框和<button>按钮。示例结构:
<template>
<view class="login-container">
<input v-model="username" placeholder="请输入用户名"/>
<input v-model="password" placeholder="请输入密码" password/>
<button @click="handleLogin">登录</button>
</view>
</template>
数据绑定与事件处理
在<script>中定义响应式数据和登录逻辑。通过v-model实现双向数据绑定,使用methods处理登录事件:

<script>
export default {
data() {
return {
username: '',
password: ''
}
},
methods: {
handleLogin() {
if (!this.username || !this.password) {
uni.showToast({ title: '请填写完整信息', icon: 'none' });
return;
}
// 调用登录API示例
uni.request({
url: 'https://api.example.com/login',
method: 'POST',
data: { username: this.username, password: this.password },
success: (res) => {
if (res.data.code === 200) {
uni.setStorageSync('token', res.data.token);
uni.reLaunch({ url: '/pages/home/index' });
}
}
});
}
}
}
</script>
样式优化
通过<style>添加样式增强用户体验,建议使用弹性布局适应不同设备:
<style>
.login-container {
padding: 40rpx;
display: flex;
flex-direction: column;
}
input {
height: 80rpx;
margin-bottom: 30rpx;
border-bottom: 1rpx solid #eee;
}
button {
background-color: #007AFF;
color: white;
}
</style>
路由配置
在pages.json中配置登录页为首页,并设置页面样式:

{
"pages": [
{
"path": "pages/login/login",
"style": {
"navigationBarTitleText": "登录"
}
}
]
}
登录状态验证
在App.vue的onLaunch中检查本地存储的token,自动跳转主页(避免重复登录):
<script>
export default {
onLaunch() {
const token = uni.getStorageSync('token');
if (token) {
uni.reLaunch({ url: '/pages/home/index' });
}
}
}
</script>
第三方登录集成
支持微信登录需调用uni.login获取code,示例代码:
methods: {
wechatLogin() {
uni.login({
provider: 'weixin',
success: (res) => {
uni.request({
url: 'https://api.example.com/wechat-auth',
data: { code: res.code }
});
}
});
}
}






