uniapp-手机登录+退出登录+第三方登录

29 手机登录+退出登录+第三方登录

一 账号邮箱手机登录

效果图:

image-20200424180327708

image-20200424180311005

思路:

1 我的页面根据loginStatus 选择是否显示登录选项。

2 大前提:没有明显的注册逻辑,直接手机号获取验证码可以登录,相当于直接注册了。

3 button的登录的时候要配置lodding 显示加载效果以及无法点击button按钮

4 两种登录方式比较像可以考虑直接进行代码整合(见代码)

5 app.vue 第一次加载的时候 初始化用户的登录状态(就是去缓存里取出来用户信息和loginStatus设置为true)。

store.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
	state:{
		loginStatus:false,
		user:{
	// 		"id": 400,
	// 		"username": "17621868045",
	// 		"userpic": null,
	// 		"password": false,
	// 		"phone": "17621868045",
	// 		"email": null,
	// 		"status": 1,
	// 		"create_time": 1587717384,
	// 		"logintype": "phone",
	// 		"token": "3e80c968d8b5610b9fda2341fd0ba43b39c59a40",
	// 		"userinfo": {
	// 			"id": 390,
	// 			"user_id": 400,
	// 			"age": 0,
	// 			"sex": 2,
	// 			"qg": 0,
	// 			"job": null,
	// 			"path": null,
	// 			"birthday": null
	// 		}
		}

	},
	mutations:{
		// 登录
		login(state,user){
			// 更改state中的变量要在这里更改。
			state.loginStatus = true
			state.user = user
			// 永久存储
			uni.setStorageSync('user',JSON.stringify(user));
		},
		
		// 初始化用户登录状态
		initUser(state){
			let user = uni.getStorageSync('user');
			if (user){
				state.user = JSON.parse(user)
				state.loginStatus = true
			}
		}
			
		}
		
		
		
	}
})

My.vue

<template>
	<view >
		<!-- 为了测试login页面 -->
		<!--
			
		</navigator> -->
		<template v-if="!loginStatus">
			<view class="flex align-center justify-center font font-weight-bold my-2">
				登录社区,体验更多功能
			</view>
			<outer-login></outer-login>
			<view class="flex align-center justify-center font text-secondary my-2" 
			hover-class="text-main"
			@click="openLogin">
				账号/邮箱/手机登录 <text class="ml-1 iconfont icon-jinru"></text>
			</view>
		</template>
	
		<view v-else class="flex px-2 py-3 align-center">
			<image :src="avator" class="rounded-circle mr-2" style="height: 100rpx;width: 100rpx;" mode=""></image>
			<view class="flex-1 flex flex-column ">
				<text class="font-lg font-weight-bold">{{user.username}}</text>
				<view class="font text-muted">
					<text class="mr-3 ">总帖子 1</text>
					<text>今日发帖 0</text>
				</view>
			</view>
			<text class="iconfont icon-jinru font-lg"></text>
		</view>
		
		
		<view class="flex align-center px-2">
			<view class="flex-1 flex flex-column align-center justify-center"
			v-for="(item,index) in myData" :key="index">
				<text class="font-lg font-weight-bold">{{item.num}}</text>
				<text class="font text-muted">{{item.name}}</text>
			</view>
		</view>
		
		<!-- 广告栏 -->
		<view class="px-2 py-3">
			<image src="/static/demo/banner2.jpg" 
			class="w-100 rounded"
			style="height: 170rpx;" mode="aspectFill"></image>
		</view>
		
		<!-- 三个小列表 -->
		<uni-list-item :show-extra-icon="true"  title="浏览历史">
			<text slot="myicon" class="iconfont icon-liulan"></text>
		</uni-list-item>
		<uni-list-item :show-extra-icon="true"  title="社区认证">
			<text slot="myicon" class="iconfont icon-huiyuanvip"></text>
		</uni-list-item>
		<uni-list-item :show-extra-icon="true"  title="审核帖子">
			<text slot="myicon" class="iconfont icon-keyboard"></text>
		</uni-list-item>
		
	</view>
</template>

<script>
	import uniListItem from '@/components/uni-ui/uni-list-item/uni-list-item.vue'
	// 导入vuex的助手函数
	import outerLogin from '@/components/common/outer-login.vue';
	import { mapState } from 'vuex'
	export default {
		components:{
			uniListItem,
			outerLogin
			
		},
		data() {
			return {
				myData:[{
					name:"帖子",
					num:1
				},{
					name:"动态",
					num:1
				},{
					name:"评论",
					num:2
				},{
					name:"粉丝",
					num:0
				}]
				
			}
		},
		// 监听导航条按钮
		onNavigationBarButtonTap(){
			uni.navigateTo({
				url:'../user-set/user-set'
			})
		},
		computed:{
			// 看这里 看这里 看这里
			// 1 放到计算属性是为了更精准的监听state里面的变化
			// 2 放到mapState里面是为了少些几行代码,相当于语法糖吧更加方便管理(当然了直接写成普通的计算属性也行)
			// 3 为了和其他的计算属性不冲突需要+...进行打散
			...mapState({
				// 4 这相当于loginStatus 是vue的那个loginstatus了 ,他地方就可以this.调用
				loginStatus:state=>state.loginStatus,
				user:state=>state.user
				// 5 如果名字一样也可以 不用对象可以直接写...mapState(['loginStatus'])
			}),
			// 6 多说一点改变vuex里面的state里面的数据,一定要用commit的形式,方便vue追踪数据变化。
			avator(){
				return this.user.userpic ? this.user.userpic : '/static/mv.png'
			}
		},
		methods: {
			// 打开登录页
			openLogin(){
				uni.navigateTo({
					url: '../login/login',
				});
			}
		}
	}
</script>

<style>

</style>

loggin.vue

<template>
	<view>
		<!-- 状态栏占位 -->
		<uni-status-bar></uni-status-bar>
		<!-- 左上角的叉 -->
		<view class="iconfont font-weight-bold icon-guanbi flex align-center justify-center font-lg" 
		style="width: 100rpx; height: 100rpx;"
		hover-class="text-muted"
		@click="back"></view>
		
		<!-- 账号密码登录 -->
		<template v-if="status">
			<view class="font-lgger flex align-center justify-center" style="margin-top:100rpx;">
				账号密码登录
			</view>
			<view class="px-2">
				<input class=" border-bottom font-md p-3" type="text"
				style="margin-top:100rpx"
				value="" placeholder="昵称/手机号/邮箱"
				 v-model="username"/>
			
				<!-- align-stretch直接保证了各个元素高度的统一,就不只是剧中对齐了 -->
				<view class="flex align-stretch border-bottom ">
					<input class="flex-1 font-md p-3" type="text"
					value="" placeholder="请输入密码" 
					v-model="password"/>
					<view class="text-muted flex  align-center justify-center" style="width: 160rpx;">
						忘记密码
					</view>
				</view>
			</view>
		</template>
		
		
		<!-- 短信验证登录 -->
		<template v-else>
			<view class="font-lgger flex align-center justify-center" style="margin-top:100rpx;">
				短信验证码登录
			</view>
			<view class="px-2">
				<!-- 手机号 -->
				<view class="flex align-center border-bottom" style="margin-top:100rpx">
					<view class="flex align-center justify-center font-weight-bold  font-md">
						+86
					</view>
					<input class="font-md p-3" type="text"
					value="" placeholder="手机号" 
					v-model="phone"/>
					<!-- <view class="flex align-center justify-center font-weight-bold bg-main">
						+86
					</view> -->
				</view>
				
				<!-- 验证码 -->
				<!-- align-stretch直接保证了各个元素高度的统一,就不只是剧中对齐了 -->
				<view class="flex align-center border-bottom ">
					<input class="flex-1 font-md p-3" type="text"
					value="" placeholder="请输入验证码" 
					v-model="code"/>
					<view class="text-white rounded flex font-md p-1 align-center justify-center bg-main " style="width: 180rpx;"
					@click="getCode"
					:class="codeTime>0 ?'bg-main-disabled':'bg-main'">
						{{codeTime>0 ? codeTime: '获取验证码'}}
					</view>
				</view>
			</view>
		</template>
		
		
		<!-- 登录按钮 -->
		<view class="px-3 " style="padding-top:60rpx">
			<button class=" text-white" style="border-radius: 50rpx;border: 0;" type="primary"
			:disabled="disabled"
			:class="disabled?'bg-main-disabled':'bg-main'"
			@click="submit"
			:loading="loading">{{loading?loading:'登录'}}</button>
			<!-- 这个loading bool一旦为true 会显示旋转加载状态并且不可点击 -->
		</view>
		
		
		
		<view class="flex align-center justify-center mx-2 my-2">
			<view class="text-primary font py-2 mx-2 " @click="changeStatus">{{status?'短信验证登录':'账号密码登录'}}</view>
			<text>|</text>
			<view class="text-primary font py-2 mx-2">登录遇到问题</view>
		</view>
		
		<view class="flex align-center justify-center py-2">
			<view class="" style="height: 1rpx;background-color: #CCCCCC;width: 100rpx;"></view>
			<view class="text-muted font">
				社交账号登录
			</view>
			<view class="" style="height: 1rpx;background-color: #CCCCCC;width: 100rpx;"></view>
		</view>
		
		<!-- 其他登录方式 -->
		<other-login></other-login>
		
		
		<view class="flex align-center justify-center mt-2">
			<text class="text-muted font">注册即代表您同意</text>
			<text class="font text-primary">《xxx社区协议》</text>
		</view>

		<!-- <view class="">
			
		</view> -->
	</view>
</template>

<script>
	import uniStatusBar from '@/components/uni-ui/uni-status-bar/uni-status-bar.vue'
	import otherLogin from '@/components/common/outer-login.vue'
	export default {
		components:{
			uniStatusBar,
			otherLogin
			
		},
		data() {
			return {
				status:true,// 账号密码验证
				username:"",
				password:"",
				phone:"",
				code:"",
				codeTime:0,
				loading:false
				
			}
		},
		computed:{
			
			disabled(){
				if((this.username===''||this.password==='')&&(this.phone===''||this.code==='')){
					return true
				}
				return false
			}
		},
		methods: {
			// 后退1页
			back(){
				uni.navigateBack({
					delta:1
				})
			},
			// 初始化表单
			initForm(){
				this.username = ''
				this.password = ''
				this.phone = ''
				this.code = ''
				
			},
			// 切换账号密码登录or短信登录
			changeStatus(){
				this.status = !this.status
				
			},
			// 获取验证码
			getCode(){
				// 防止重复获取
				if (this.codeTime>0){
					return;
				}
				// 验证手机号
				if (!this.validate()) return;
				// 请求数据
				this.$H.post('/user/sendcode',{
					phone:this.phone
				},{
					// 这样原生数据就会传输过来
					native:true
				}).then(res=>{
					// console.log(res)
					uni.showToast({
						title:res.data.msg,
						icon:'none'
					})
				}).catch(err=>{
					// console.log(err)
				})
				
				// 倒计时
				this.codeTime = 5
				// 箭头函数可以直接拿到外面的this的内容
				let timer = setInterval(()=>{
					if (this.codeTime >= 1){
						this.codeTime--
					} else{
						clearInterval(timer)
					}
				},1000)
				
			},
			// 表单验证
			validate(){
				//手机号正则 只是针对验证码的手机号字段,其他并未做兼容。
				var mPattern = /^1[34578]\d{9}$/; 
				if (!mPattern.test(this.phone)) {
					uni.showToast({
						title: '手机号格式不正确',
						icon: 'none'
					});
					return false
				}
				// ...更多验证
				return true
			},
			// 提交
			submit(){
				this.loading = '登录中...'
				let url = ""
				let data = ""
				// 表单验证
				if(!this.status){
					if (!this.validate()) return;
				}
				if (this.status){
					// 账号密码登录
					url = '/user/login'
					data = {
						username:this.username,
						password:this.password
					}
				}else{
					
					// 手机验证码登录
					url = '/user/phonelogin'
					data = {
						phone:this.phone,
						code:this.code
					}
				}
				
				// 提交后端
				this.$H.post(url,data).then(res=>{
					// console.log(res)
					// 修改vuex的state,持久化存储
					this.$store.commit('login',res)
					// 提示和跳转
					uni.navigateBack({
						delta:1
					})
					uni.showToast({
						title:'登录成功',
						icon:'none'
					})
					this.loading = ''
				}).catch(
					this.loading = ''
				)
				// 登录成功处理
			}
		
		}
	}
</script>

<style>

</style>

App.vue

<script>
export default {
	onLaunch: function() {
		console.log('App Launch');
		// 检测更新
		this.$U.update()
		// 网络更新
		this.$U.onNetWork()
		// 初始化数据
		// 初始化用户登录状态
		this.$store.commit('initUser')
	},
	onShow: function() {
		console.log('App Show');
	},
	onHide: function() {
		console.log('App Hide');
	}
};
</script>

<style>
	/*每个页面公共css */
	/* 官方css库 */
	@import "./common/uni.css";
	/* 自定义图标库 */
	@import "./common/icon.css";
	/* 动画库 */
	@import "./common/animate.css";
	/* @import url("./common/ceshi.css"); */
	/* 引入自定义的css库 */
	@import "./common/free.css";
	/* 引入自定义本项目相关的css库 */
	@import "./common/common.css";
/* 解决头条小程序组件内引入字体不生效的问题 */
/* #ifdef MP-TOUTIAO */
@font-face {
	font-family: uniicons;
	src: url('/static/uni.ttf');
}
/* #endif */


	
</style>

二 退出登录

效果图:

image-20200424180114994

image-20200424180134925

点击确定回到了首页,再次进到设置里一看只有这两个功能了。

image-20200424180022978

思路:

1 既然有退出登录,就要考虑设置里面哪些是登录了才可以显示的。

2 退出登录就是设置loginState的状态为false、user={}, 清除本地缓存。

User-set.vue

<template>
	<view>
		<!-- // 登录可见 -->
		<template v-if="loginStatus">
			<uni-list-item title="账号与安全" @click="open('user-password')"></uni-list-item>
			<uni-list-item title="绑定邮箱" @click="open('user-email')"></uni-list-item>
			<uni-list-item title="资料编辑" @click="open('user-userinfo')"></uni-list-item>
		</template>
		
		<!-- // 非登录可见 -->
		<uni-list-item title="清除缓存" @click="clear" class="text-muted"><text slot="right_content">{{currentSize | formatSize}}</text></uni-list-item>
		
		<!-- // 登录可见 -->
		<uni-list-item v-if="loginStatus" title="意见反馈" @click="open('user-feedback')"></uni-list-item>
		
		<!-- // 非登录可见 -->
		<uni-list-item title="关于社区" @click="open('about')"></uni-list-item>
		
		<!-- // 登录可见 -->
		<view  v-if="loginStatus" class="py-3 px-2">
			<button type="primary" 
			class="bg-main rounded text-white"  
			style="border-radius: 50rpx;"
			@click="logout">退出登陆</button>
		</view>
	</view>
</template>

<script>
	import uniListItem from '@/components/uni-ui/uni-list-item/uni-list-item.vue'
	import {mapState} from 'vuex'
	export default {
		components:{
			uniListItem
		},
		data() {
			return {
				currentSize:0
			}
		},
		computed:{
			...mapState({
				loginStatus:state=>state.loginStatus
			})
		},
		onLoad() {
			this.getStorageInfo()
		},
		filters:{
			formatSize(value){
												//保留1位小数 
				return value>1024? (value/1024).toFixed(1)+' MB':value.toFixed(1)+' KB';
			}
		},
		methods: {
			open(path){
				uni.navigateTo({
					url:`../${path}/${path}`
				})
			},
			getStorageInfo(){
				// 获取缓存信息
				let res = uni.getStorageInfoSync()
				// console.log(res)
				this.currentSize = res.currentSize
			},
			// 清除缓存信息
			clear(){
				uni.showModal({
					title:'提示',
					content:'是否要清除所有缓存?',
					cancelText:'不清除',
					confirmText:'清除',
					confirmColor:'#FF4A6A',
					success: (res) => {
						if(res.confirm){
							// 清除所有本地缓存
							uni.clearStorage()
							// 更新最新的缓存信息
							this.getStorageInfo()
							// 提示一下
							uni.showToast({
								title:'清除成功',
								icon:'none'
							})
						}
					}
				})
			},
			
			// 退出登录
			logout(){
				// 询问是否退出登录?
				uni.showModal({
					content:'是否要退出登录',
					success:(res) => {
						if (res.confirm) {
							this.$store.commit('logout')
							uni.navigateBack({
								delta:1
							})
							uni.showToast({
								title:"退出登录成功",
								icon:'none'
							})
						}
					}
				})
			}
		}
	}
</script>

<style>

</style>

Store/index.js(只看退出登录注释就行了)

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
	state:{
		loginStatus:false,
		user:{
	// 		"id": 400,
	// 		"username": "17621868045",
	// 		"userpic": null,
	// 		"password": false,
	// 		"phone": "17621868045",
	// 		"email": null,
	// 		"status": 1,
	// 		"create_time": 1587717384,
	// 		"logintype": "phone",
	// 		"token": "3e80c968d8b5610b9fda2341fd0ba43b39c59a40",
	// 		"userinfo": {
	// 			"id": 390,
	// 			"user_id": 400,
	// 			"age": 0,
	// 			"sex": 2,
	// 			"qg": 0,
	// 			"job": null,
	// 			"path": null,
	// 			"birthday": null
	// 		}
		}

	},
	mutations:{
		// 登录
		login(state,user){
			// 更改state中的变量要在这里更改。
			state.loginStatus = true
			state.user = user
			// 永久存储
			uni.setStorageSync('user',JSON.stringify(user));
		},
		
		// 初始化用户登录状态
		initUser(state){
			let user = uni.getStorageSync('user');
			if (user){
				state.user = JSON.parse(user)
				state.loginStatus = true
			}
		},
		
		// 退出登录
		logout(state){
			state.loginStatus = false
			state.user = {}
			uni.removeStorageSync('user')
			
		}	
	}
})

三 第三方登录

效果图:

image-20200506124333031

image-20200506124258818

思路:

以微信第三方登录为案例:

1 点击微信图标

2 像微信后台发送两次请求拿到openid和头像等信息。

3 把拿到的信息发送到我们的后台。

4 后台存储后发送到前台,前台把拿到的后台返回来的信息进行本地存储。

5 然后看情况提示以及返回上一页操作

代码:

<template>
	<view>
		<view class="flex align-center justify-between" style="padding:20rpx 100rpx">
			<view 
			v-for="(item,index) in providerList" :key="index"
			class="iconfont text-white font-lgger rounded-circle flex align-center justify-center" 
			style="height:100rpx;width:100rpx;"
			:class="item.icon+' '+item.bgColor"
			@click="login(item)"> 
			<!-- 如果直接写了函数就会直接调用 :login="login(item)"-->
			<!-- 完善login函数 实现第三方登录。 -->  
				
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		props:{
			back:{
				type:Boolean,
				default:false
				
			}
		},
		data() {
			return {
				providerList: []
			}
		},
		mounted() {
			uni.getProvider({
				service: 'oauth',
				success: (result) => {
					// console.log(result.provider)
					this.providerList = result.provider.map((value) => {
						let providerName = '';
						let icon = ''
						let bgColor = ''
						switch (value) {
							case 'weixin':
								providerName = '微信登录'
								// 自己在这个位置添加上需要渲染的信息 如 icon bgColor
								icon = 'icon-weixin'
								bgColor = 'bg-success'
								break;
							case 'qq':
								providerName = 'QQ登录'
								icon = 'icon-QQ'
								bgColor = 'bg-primary'
								break;
							case 'sinaweibo':
								providerName = '新浪微博登录'
								icon = 'icon-xinlangweibo'
								bgColor = 'bg-warning'
								break;
						}
						// 返回的时候
						return {
							name: providerName,
							id: value,
							icon:icon,
							bgColor:bgColor
						}
					});
		
				},
				fail: (error) => {
					console.log('获取登录通道失败', error);
				}
			});
		},
		methods: {
			// 登录
			login(item){
				console.log('###',item)
				// 微信需要先login一下,才能执行里面的uni.getUserInfo
				// 这个uni.login的工具函数,可以渲染出来微信登录的页面
				uni.login({
					provider:item.id,
					success:res => {
						console.log(res)
						// 获取用户信息
						uni.getUserInfo({
							provider:item.id,//'weixin'
						    success:(infoRes) =>{
								// console.log('####',infoRes)
								// {
								// 	"errMsg": "getUserInfo:ok",
								// 	"userInfo": {
								// 		"openId": "oRrdQtzJovVH1ZbCqvf9rQ",
								// 		"nickName": "不争",
								// 		"gender": 1,
								// 		"city": "白山",
								// 		"province": "吉林",
								// 		"country": "中国",
								// 		"avatarUrl": "http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJYwJfvYwOp29uZAvfRoPSMvo357ibaGh79IdZ40ja3kQS9Sp7VTWhUHcg/132",
								// 		"unionId": "oU5YytxKvy2K0oUftFxmm4"
								// 	}
								// }
								let obj = {
									provider:item.id, // weixin/weibo/qq
									openid :infoRes.userInfo.openId,// 唯一id
									expires_in:0,// 过期时间
									nickName:infoRes.userInfo.nickName, // 微信的昵称
									avatarUrl:infoRes.userInfo.avatarUrl// 微信头像地址
								}
								console.log(obj)
								// 从微信/qq拿到的信息提交给后端。
								this.loginEvent(obj)
								
							},	
							
						})
					}
				})
			},
			
			// 拿到第三方来的登录信息请求后端。
			loginEvent(data){
				this.$H.post('/user/otherlogin',data)
				.then(res=>{
					// 修改vuex的state,持久化存储
					this.$store.commit('login',this.$U.formatUserinfo(res))
					
					// 返回上一页
					if (this.back){
						uni.navigateBack({
							delta:1
						})
					}
					uni.showToast({
						title:'登录成功',
						icon:'none'
					})	
				})
			}
		}
	}
</script>

<style>

</style>

posted @ 2020-05-25 18:09  张明岩  阅读(11716)  评论(0编辑  收藏  举报