当前位置: 首页 > news >正文

微信小程序(黑马优购:登录)

1.点击结算进行条件判断

user.js

  //数据
  state: () =>({
    // address: {}
    address: JSON.parse(uni.getStorageSync('address') || '{}'),
    token: ''
  }),

 my-settle.vue

  computed: {
      ...mapGetters('m_cart',['checkedCount','total','checkedGoodsAmount']),
      ...mapGetters('m_user',['addstr']),
      ...mapState('m_user',['token'])

  //用户点击了结算按钮
      settlement(){
        if(!this.checkedCount) return uni.$showMsg('请选择要结算的商品!')
          
        if(!this.addstr) return uni.$showMsg('请选择收货地址')
        
        if(!this.token) return uni.$showMsg('请先登录!')
      }

2.创建登录(my-login)和用户信息组件(my-userinfo)

my-login.vue

 //绘制底部半圆的造型
    &::after{
      content: ' ';
      display: block;
      width: 100%;
      height: 40px;
      background-color: white;
      position: absolute;
      bottom: 0;
      left: 0;
      border-radius: 100%;
      //往下移50%
      transform: translateY(50%);
    }

3.登录授权

如果没有显示下面的弹框,基础库设置为最低版本即可

  methods:{
      //用户授权之后,获取用户的基本信息
      getUserinfo(e){
        console.log(e);
        if(e.detail.errMsg === 'getUserInfo:fail auth deny') return uni.$showMsg('您取消了登录授权!')
      }
    }

 3.将用户的基本信息存储到Vuex

  //数据
  state: () =>({
    // address: {}
    address: JSON.parse(uni.getStorageSync('address') || '{}'),
    token: '',
    //用户的信息对象
    userinfo: JSON.parse(uni.getStorageSync('userinfo') || '{}')
  }),

  saveUserInfoToStorage(state){
      uni.setStorageSync('userinfo',JSON.stringify(state.userinfo))
    }

 my-login.vue

<script>
  import {mapMutations} from 'vuex'
  export default {
    data() {
      return {
        
      };
    },
    methods:{
      ...mapMutations('m_user',['updateUserInfo']),
      //用户授权之后,获取用户的基本信息
      getUserinfo(e){  
        if(e.detail.errMsg === 'getUserInfo:fail auth deny') return uni.$showMsg('您取消了登录授权!')
        console.log(e.detail.userInfo);
        this.updateUserInfo(e.detail.userInfo)
      }
    }
    
  }
</script>

4.调用uni.login

1)拿到code值

  //用户授权之后,获取用户的基本信息
      getUserinfo(e){  
        if(e.detail.errMsg === 'getUserInfo:fail auth deny') return uni.$showMsg('您取消了登录授权!')
        console.log(e.detail.userInfo);
        this.updateUserInfo(e.detail.userInfo)
        this.getToken(e.detail)
      },
      async getToken(info){
        //获取code对应的值
        const [err,res] = await uni.login().catch(err => err)
        console.log(res);
        if( err || res.errMsg !== 'login:ok'){
          return uni.$showMsg('登录失败!')
        }
        console.log(res.code);
        console.log(info);
      } 
      

user.js

token: uni.getStorageInfoSync('token') || '',

updateToken(state,token){
      state.token = token
      this.commit('m_user/saveTokenToStorage')
    },
    saveTokenToStorage(state){
      uni.setStorage('token',state.token)
    }

...mapMutations('m_user',['updateUserInfo','updateToken']),

2)持久化存储token

await uni.$http.post('/api/public/v1/users/wxlogin',query)这里的接口不能获取到token值,

直接把token写死

my-login.vue

 data() {
      return {
         token : 'abc147258369jkl'
      };
    },

   async getToken(info){
        //获取code对应的值
        const [err,res] = await uni.login().catch(err => err)
        console.log(info);
        if( err || res.errMsg !== 'login:ok'){
          return uni.$showMsg('登录失败!')
        }
         console.log(res);
        //准备参数
        const query = {
          code: res.code,
          encryptedData: info.encryptedData,
          iv: info.iv,
          rawData: info.rawData,
          signature: info.signature
        }
       const { data: loginResult } = await uni.$http.post('/api/public/v1/users/wxlogin',query)
       console.log(loginResult);
       if(loginResult.meta.status !== 200 ) {
             uni.$showMsg('登录成功')
              uni.setStorageSync('token',this.token);
             this.updateToken(this.token)
       }

4.获取用户信息

渲染头像和名称

<view class="top-box">
          <image :src="userinfo.avatarUrl" class="avatar"></image>
          <view class="nickname">{{userinfo.nickname}}</view>
      </view>

import { mapState } from 'vuex' 

computed:{
      ...mapState('m_user',['userinfo'])
    }

5.退出登录

  methods:{
      ...mapMutations('m_user',['updateAddress','updateUserInfo','updateToken']),
      async logout(){
        const [err,succ] = await uni.showModal({
          title: '提示',
          content: '确认退出登录吗?'
        }).catch(err => err)
        if(succ && succ.confirm){
          this.updateAddress({})
          this.updateUserInfo({})
          this.updateToken('')
        }
      }
      

6.如果用户没有登录,则3秒后自动跳转到登录页面

my-settle.vue

   return {
        //倒计时的秒数
        seconds: 3,
        //定时器的Id
        timer: null
      };

 //延时导航到my页面
      delayNavigate(){

        this.seconds = 3
          this.showTips(this.seconds)
          this.timer = setInterval(()=>{
            this.seconds--
            if(this.seconds <= 0){
              clearInterval(this.timer)
              uni.switchTab({
                url: '/pages/my/my'
              })
              return
            }
            this.showTips(this.seconds)
          },1000)
      },

 //展示倒计时的提示消息
      showTips(n){
        uni.showToast({
          icon: 'none',
          title: '请登录后再结算! '+n+' 秒之后自动跳转到登录页',
          mask: true,
          duration: 1500
        })
      

7.登录成功之后再返回之前的页面

user.js

  //重定向的Object对象
    redirectInfo: null

  updateRedirectInfo(state,info){
      state.redirectInfo = info
      console.log(state.redirectInfo);
    }

my-login.vue

   computed:{
        ...mapState('m_user',['redirectInfo'])
    },

.methods:{
      ...mapMutations('m_user',['updateUserInfo','updateToken','updateRedirectInfo']),

  if(loginResult.meta.status !== 200 ) {
             uni.$showMsg('登录成功')
             this.updateToken('abc147258369jkl')
             this.navigateBack()
       }

 navigateBack(){
        // this.redirectInfo.openType === 'switchTab':重定向的方式是switchTab
        if(this.redirectInfo && this.redirectInfo.openType === 'switchTab'){
          uni.switchTab({
            url:this.redirectInfo.from,
            complete: ()=>{
              this.updateRedirectInfo(null)
            }
          })
        }
      }

my-settle.vue

 //延时导航到my页面
      delayNavigate(){
          this.seconds = 3
          this.showTips(this.seconds)
          this.timer = setInterval(()=>{
            this.seconds--
            if(this.seconds <= 0){
              clearInterval(this.timer)
              uni.switchTab({
                url: '/pages/my/my',
                success: () => {
                  this.updateRedirectInfo({
                    openType: 'switchTab',
                    from: '/pages/cart/cart'
                  })
                }

相关文章:

  • 百度资源平台链接提交
  • HTML表格
  • 从大厂裸辞半年,我靠它成功赚到了第一桶金,如果你失业了,建议这样做,不然时间太久了就完了
  • ChatGPT如何升级为GPT-4在国内
  • 【蓝桥杯嵌入式】六、真题演练(一)-1演练篇:第 届真题
  • 壁纸小程序Vue3(分类页面和用户页面基础布局)
  • 大型语言模型可以“在两年内彻底改变金融业”
  • 常用VPS服务器检测脚本
  • 蓝桥杯省赛刷题——题目 2656:刷题统计
  • 维修贝加莱4PP420.1043-B5触摸屏Power Panel 400工业电脑液晶
  • Day54:WEB攻防-XSS跨站Cookie盗取表单劫持网络钓鱼溯源分析项目平台框架
  • T2最长的AB序列(20分) - 京东前端笔试编程题题解
  • 拿到运营商给的IP池
  • 课时81:流程控制_循环控制_continue实践
  • go: go.mod file not found in current directory or any parent directory.如何解决?
  • 分享一款快速APP功能测试工具
  • CentOS 7 修改主机名
  • Just for fun——迅速写完快速排序
  • leetcode讲解--894. All Possible Full Binary Trees
  • Linux各目录及每个目录的详细介绍
  • Redux 中间件分析
  • Shell编程
  • SpiderData 2019年2月23日 DApp数据排行榜
  • tensorflow学习笔记3——MNIST应用篇
  • Transformer-XL: Unleashing the Potential of Attention Models
  • UEditor初始化失败(实例已存在,但视图未渲染出来,单页化)
  • use Google search engine
  • 阿里云容器服务区块链解决方案全新升级 支持Hyperledger Fabric v1.1
  • 笨办法学C 练习34:动态数组
  • 闭包,sync使用细节
  • 大整数乘法-表格法
  • 第十八天-企业应用架构模式-基本模式
  • 个人博客开发系列:评论功能之GitHub账号OAuth授权
  • 基于Dubbo+ZooKeeper的分布式服务的实现
  • 开源中国专访:Chameleon原理首发,其它跨多端统一框架都是假的?
  • 力扣(LeetCode)56
  • 两列自适应布局方案整理
  • 聊聊sentinel的DegradeSlot
  • 嵌入式文件系统
  • 什么是Javascript函数节流?
  • MiKTeX could not find the script engine ‘perl.exe‘ which is required to execute ‘latexmk‘.
  • ​水经微图Web1.5.0版即将上线
  • (BFS)hdoj2377-Bus Pass
  • (done) 两个矩阵 “相似” 是什么意思?
  • (附源码)springboot建达集团公司平台 毕业设计 141538
  • (附源码)小程序儿童艺术培训机构教育管理小程序 毕业设计 201740
  • (收藏)Git和Repo扫盲——如何取得Android源代码
  • (四)七种元启发算法(DBO、LO、SWO、COA、LSO、KOA、GRO)求解无人机路径规划MATLAB
  • (五)MySQL的备份及恢复
  • (转)shell中括号的特殊用法 linux if多条件判断
  • *Algs4-1.5.25随机网格的倍率测试-(未读懂题)
  • .htaccess配置重写url引擎
  • .Net FrameWork总结
  • .net 中viewstate的原理和使用
  • .NET/C# 的字符串暂存池