uniapp入门级最佳实践(四) | 8月更文挑战

408 阅读4分钟

这是我参与8月更文挑战的第21天,活动详情查看:8月更文挑战

一、授权登录分为H5和小程序

1、H5授权登录

我这里H5登录分为六个步骤,比较麻烦,相比小程序真的复杂多了

  •   拿到微信的用户code

         在onLoad生命周期中获取code,并且判断是不是有code没有code进行重定向,有code进行登录就是下面的步骤

onLoad(options) {
	//1、获取微信生成的code
	if(this.$utils.getUrlParam('code')) {
		this.code = this.$utils.getUrlParam('code');
		this.goLogin();
	}else {
		let localUrl = encodeURIComponent(window.location.href);  //获取当前页面地址
		window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+getApp().globalData.appid +
			"&redirect_uri=" +localUrl +"&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
	}
}
  • 调接口登录判断是否需要绑定手机号(因为我们必须要绑定手机号)

    //登录方法 uni.request({ // 请求路径 url: getApp().globalData.serverUrl+'/wxLogin', // 请求参数code data: { appId: getApp().globalData.appid, code: _this.code }, method: 'GET', success(res){ getApp().globalData.token = res.data.token; uni.setStorage({ key: 'token', data: res.data..token });

    	//3、获取用户手机号码
    	if(res.data.mobilePhone) {
    		uni.setStorage({
    			key: 'userPhone',
    			data: res.data.mobilePhone
    		});
    		getApp().globalData.userPhone = res.data.data.mobilePhone;
    		uni.switchTab({
    			url: '/pages/index/index'
    		});
    	}else{
    		//3、获取用户手机号码
    		_this.isShowPhone = true;//展示获取手机号登录的页面模块
    		_this.changeImgCode();//4、展示图形验证码
    	}
    }
    

    });

  • 需要绑定手机号就要做验证,不需要就进首页

这里就是通过变量展示出输入手机号码的页面

  • 获取图形验证码

图形验证码一般是用随机数获取到,以前写过一篇随机数的文章,也可以直接获取当前时间戳进行代替,设计隐私不展示接口的调用方式

  • 发送验证码倒计时

    data() { return { messageCode: '',//短信验证码 isSendMessage: false,//判断是否发送验证码 sendMessageTxt:'获取验证码',//发送验证码按钮展示文字 timeWaitNum: 60, } }, methods: { //5、发送短信验证码 sendMessage() { let _this = this; //验证手机号是否输入等 //调用接口发送验证码 uni.request({ url: '/doSendSmsV2',// 请求参数code data: { mobilePhone: _this.mobilePhone }, method: 'GET', success(res){ _this.calculateTime();//计算倒计时 } }) }, //倒计时验证码 calculateTime() { let _this = this; if (this.timeWaitNum == 0) { this.isSendMessage = false; this.sendMessageTxt = '获取验证码'; this.timeWaitNum = 60; return; } else { this.isSendMessage = true; this.sendMessageTxt = this.timeWaitNum+'s后重试'; this.timeWaitNum--; } setTimeout(()=> { _this.calculateTime(); },1000) //每1000毫秒执行一次 } }

页面表格动态展示文字内容,以60s为基础倒计时并且禁止按钮点击,然后调用接口后通过递归的方式进行每一秒判断倒计时是否等于0,不等于0就继续递归调用把文本时间减一进行展示,否则就允许按钮重新点击

<view class="uni-form-item uni-column flex inputBox2">
	<input class="uni-input inputVal" style="width: 60%;" type="number" v-model="messageCode" placeholder="请输入短信验证码" />
	<button class="sendMessageBtn" v-if="!isSendMessage" @click="sendMessage()">获取验证码</button>
	<button class="sendMessageBtn" v-else>{{sendMessageTxt}}</button>
</view>
  • 调用登录接口

这里就和第二步一样,把接口需要的参数穿过去,然后保存token和用户信息即可。

以上就是H5登录的流程,一开始看到那么多步骤感觉还是挺麻烦的,现在整理一下感觉还可以,主要就是获取图形验证码和短信验证码倒计时这里逻辑写的麻烦。

  • 小程序授权登录

    <button class="loginBtnBox" @click="getUserInfo">授权登录 <button class="loginBtnBox flex" v-if="isShowPhone" open-type="getPhoneNumber" lang="zh_CN" @getphonenumber="getPhoneNumberHandler">获取手机号码

    //获取用户信息 getUserInfo(){ uni.getUserProfile({ desc:'Wexin', // 这个参数是必须的 success:res=>{ this.userInfo = res.userInfo; //这里可以拿到用户头像昵称信息 uni.login({ success (res1) { //发起网络请求,拿到code给后端请求正式登录 } }); }, fail:err=>{ console.log(err) } }) }, // 手机登录时获取手机号码相关信息的函数 getPhoneNumberHandler(e) { console.log(e); //这里可以获取参数encryptedData、iv、unionId、openID、session_key //请求接口把这些参数传给接口 }

这里的button一定要这种方式写,不然就不起作用,看了很多文档,试了好几次,小程序的授权登录真的简单多了。

二、列表上滑分页

<block v-if="dataList.length > 0">
	<scroll-view :scroll-y="isScroll" :style="{ height: windowHeight + 'px' }" @scrolltolower="scrolltolowerHandler" :scroll-top="scrollTop">		<view v-for="item,index in dataList" :key="index" class="messageItem">
			{{item.name}}
		</view>
	</scroll-view>
</block>
<view v-else class="noDataTxt">暂无数据</view>

js:

data() {
	return {
		dataList: [],
		isScroll: true,
		windowHeight: 0,
		scrollTop: 0,
		page: 1,
		limit: 10,
		hasMoreData: false,//是否还有更多数据
	}
},
onLoad() {
	let _this = this;
	wx.getSystemInfo({
		success: function(res) {
			_this.windowHeight = res.windowHeight;
		}
	})
}
onShow() {
	this.searchList();
},
methods: {
	searchList() {
		let _this = this;
		_this.$utils.requestFun('/searchList', {
			token: getApp().globalData.token,
			page: _this.page,
			limit: _this.limit
		}, 'GET').then(res => {
			let resData = _this.dataList;
			if(res.data.data.data && res.data.data.data.length > 0) {
				if(_this.page == 1) {
					resData = [];
				}
				let dataList = res.data.data.data;
				if(dataList.length < _this.limit) {
					_this.dataList = resData.concat(dataList);
					_this.hasMoreData = false;
				}else {
					_this.dataList = resData.concat(dataList);
					_this.hasMoreData = true;
					_this.page = _this.page++;
				}
			}else {
				if(_this.page == 1) {
					_this.dataList = [];
				}else {
					_this.dataList = resData;
				}
			}
		});
	},
	scrolltolowerHandler(e) {
		if (this.hasMoreData) {
			let page = this.page+1;
			this.page = page;
			this.searchList();
		} else {
			uni.showToast({
				title: '没有更多数据',
				icon: 'none'
			})
		}
	}
}

感觉写了各种版本的分页,在手机上使用scroll-view的感受是真的比不用好很多,用scroll-view很顺滑,触发的很快,因为是自带的方法,scrolltolower是scroll-view自带的方法,判断触底/右边触发事件,也就是上拉触底后会调用的事件,我这里用了hasmoreData变量判断是否还有更多数据,触底的时候页数+1或者就提示暂无更多数据。

调用接口的地方判断返回数据是否大于0,或者页数来判断是否要和现有的数据合并到一起。