微信小程序 登录优化

这个可以分为2中方式

第一种:在util.js文件里写

第二种:在app.js文件里写

 

第一种:在util.js文件里写

util.js文件

//登录 检测
//检测登录
function cp_login_if() {
  let uid = wx.getStorageSync('uid');
  // 根据缓存信息判断是否登录
  if (!uid) {
    console.log('未登录') 
    wx.hideLoading();
    wx.showModal({
      title: "未登录", content: "是否登录", showCancel: true, cancelText: "回到首页", confirmText: "去登录", cancelColor: "#858484", confirmColor: "#ff5816",
      success: (res) => {
        console.log("====显示模态对话框  是否授权====")
        console.log(res)
        var cancel = res.cancel, confirm = res.confirm;
        if (confirm) { 
          wx.navigateTo({ url: '/pages/login/login'});
        } else if (cancel || cancel == false) {
          wx.switchTab({ url: '/pages/index/index' })
        }
      }
    }) 
    return false;
  } else {
    // 正常登录后逻辑
    return true;
  }
}


module.exports = { 
  cp_login_if: cp_login_if
}

 在Util.js写的函数和变量,想要外部文件引用后可用,必须在module.exports暴露下;(或者说声明下)

其他.js文件调用

第一步:顶部引入

var util = require('../../utils/util.js');

注意:一定是在page({})上面,引入

第二步:调用

 //登录检测
    if (!util.cp_login_if()){
      return;
    }

 

第二种:在app.js文件里写

app.js文件

App({

  //判断用户是否登录
   cp_login_if() {
     console.log('检测登录')
     let useruid = wx.getStorageSync('uid');
    // 根据缓存信息判断是否登录
     if (!useruid) {
       console.log('未登录')
       var _this = this; 
       wx.hideLoading();
       wx.showModal({
         title: "提示", content: "您还没有登录", showCancel: true, cancelText: "回到首页", confirmText: "去登录", cancelColor: "#858484", confirmColor: "#ff5816",
         success: (res) => {
           console.log("====显示模态对话框  是否授权====")
           console.log(res)
           var cancel = res.cancel, confirm = res.confirm;
           if (confirm) { 
             //去登陆 
               wx.redirectTo({
                       url: '/pages/login/login'
                })
           } else if (cancel || cancel == false) {
             wx.switchTab({ url: '/pages/index/index' })
           }
         }
       })
   
    }else{
       console.log('已登录')
      return true
    }
  },
//判断用户是否登录--结束

})

 

其他.js文件调用

第一步:顶部引入

const app = getApp();

注意:一定是在page({})上面,引入

第二步:调用

// 登录验证
app.cp_login_if()

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

橙-极纪元JJY.Cheng

客官,1分钱也是爱,给个赏钱吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值