uni-app实现公众号登陆实现
公众号实现登陆流程思路:
1. 创建一个页面用于登陆,页面上需要有输入账号和密码的表单,以及登陆按钮。
2. 在登陆按钮的点击事件中,调用后端接口进行账号密码校验。如果校验通过,则将后端返回的用户信息保存在本地存储中。
3. 在需要使用用户信息的页面中,可以通过 uni.getStorageSync 方法获取本地存储中的用户信息,判断用户是否已经登陆。如果本地存储中没有用户信息,则跳转到登陆页面。
下面是具体的代码实现:
1. 登陆页面的模板代码
<template> <view class="login"> <view class="form-group"> <view class="label">账号:</view> <input type="text" v-model="username" placeholder="请输入账号" /> </view> <view class="form-group"> <<view class="label">密码:</view> <input type="password" v-model="password" placeholder="请输入密码" /> </view> <button type="primary" class="login-btn" @click="handleLogin">登陆</button> </view> </template>
```
2. 在登陆按钮的点击事件中,调用后端接口进行账号密码校验。
```
methods: { async handleLogin() { try { const res = await uni.request({ url: 'http://yourbackend.com/login', method: 'POST', data: { username: this.username, password: this.password } }); if (res.code === 0) { uni.setStorageSync('userInfo', res.data); //将用户信息保存在本地 uni.showToast({ title: '登陆成功!', icon: 'success' }); uni.navigateTo({ url: '/pages/home/index' }); } else { uni.showToast({ title: '登陆失败,请检查账号密码是否正确!', icon: 'none', duration: 2000 }); } } catch (err) { console.log('登陆失败', err); uni.showToast({ title: '登陆失败,请稍后再试!', icon: 'none', duration: 2000 }); } } },
```
3. 在需要使用用户信息的页面中,可以通过 uni.getStorageSync 方法获取本地存储中的用户信息,判断用户是否已经登陆。
```
onShow() { const userInfo = uni.getStorageSync('userInfo'); if (!userInfo) { uni.navigateTo({ url: '/pages/login/index' }); } else { this.userInfo = userInfo; } }
```
以上代码示例中,我们使用 uni.request 方法发送登陆请求,通过 await 等待后端返回数据,根据返回码来判断登陆是否成功。如果成功,则将用户信息保存在本地存储中,并跳转到首页(/pages/home/index)。如果失败,则提示错误信息。
在首页中,我们使用 onShow 方法来获取本地存储中的用户信息,如果不存在,则跳转到登陆页面(/pages/login/index)。
注意,这里存储的用户信息是明文存储的,如果存储的信息中包含敏感信息,建议对数据进行加密保存