首页 > 编程知识 正文

微信小程序登陆组件封装失败,微信小程序容器组件

时间:2023-05-03 23:57:12 阅读:267152 作者:4942

微信小程序登陆组件封装 // 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_idif (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.dataif (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>

前端进阶精选:点此去

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。