微信小程序登陆组件封装

微信小程序登陆组件封装

// components/login/login.js
//获取应用实例
const app = getApp();
var $http = require('../../utils/http.js');
var util = require('../../utils/util.js');
Component({
/**
* 组件的属性列表
*/
properties: {

},

/**
* 组件的初始数据
*/
data: {

},

attached: function () { //检测有没有缓存到user_id
	if (wx.getStorageSync("user_id")){
		//已登录
	}else{
		this.check();
	}
},
/**
* 组件的方法列表
*/
methods: {
/***
* 
* 登录相关
*/
//显示登录或授权提示
showLoginModal: function () {
	this.setData({
	settingShow: true
	});
wx.hideTabBar();
},
//判断是否登录
check: function (cb) {
	console.log('登录')
	var that = this;
	wx.getSetting({
	success: function (res) {
		if (res.authSetting['scope.userInfo']) {

			// 已经授权,可以直接调用 getUserInfo 获取头像昵称
			console.log('已经授权');
			wx.getUserInfo({
			withCredentials: true,
			success: function (res) {
			that.setData({
			settingShow: false
		})
		wx.showTabBar();

		that.login();
	},
	fail: function () {
	that.showLoginModal();

}
});
	} else {
	that.showLoginModal();

}
},
fail: function () {
that.showLoginModal();
}
});

},
login: function () {
	var that = this;
	var token = wx.getStorageSync('token') || '';
	//调用登录接口
	wx.login({
	success: function (res) {
	if (res.code) {
	//发起网络请求
	wx.getUserInfo({
	success: function (ures) {
	wx.request({
	url: app.globalData.url + 'user/login',
	data: {
	code: res.code,
	rawData: ures.rawData,
	token: token
	},
	method: 'post',
	header: {
	"Content-Type": "application/x-www-form-urlencoded",
},
success: function (lres) {
	var response = lres.data
	if (response.code == 1) {
	that.data.userInfo = response.data.userInfo;
	// that.updateGlobalData(response.data);
	wx.setStorageSync('token', response.data.userInfo.token)
	// wx.setStorageSync('userInfo', response.data.userInfo);
	wx.setStorageSync('user_id', response.data.userInfo.user_id);
	// typeof cb == "function" && cb(response.data.userInfo);

	//刷新当前页面
	var pages = getCurrentPages();
	var prevPage = pages[pages.length - 1]; //当前页面)
	// prevPage.onLoad()
	prevPage.onPullDownRefresh(); //重新刷新页面
	} else {
	wx.setStorageSync('token', '');
	console.log("用户登录失败")
	that.showLoginModal();
}
}
});
},
fail: function (res) {
that.showLoginModal();
}
});
} else {
that.showLoginModal();
}
}
});
},
getuserinfo: function (e) {
	if (!e.detail.userInfo) {

	} else {
	this.setData({
	settingShow: false
});
	this.check();
}

},
}
})

方法已经封装好,哪个页面需要授权登陆就可以把次组件引入到对应的页面就可以了。

方法:
1.在需要引入组件页面的.json文件中定义好模板名称和路径
2.在.wxml页面中引入组件
<login></login>

前端进阶精选:点此去

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值