首页 > 编程语言 >微信小程序(黑马优购:登录)

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

时间:2024-03-29 22:59:49浏览次数:22  
标签:return 登录 优购 微信 token user uni my 黑马

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'
                  })
                }

标签:return,登录,优购,微信,token,user,uni,my,黑马
From: https://blog.csdn.net/jklzbc/article/details/137153812

相关文章

  • 黑马鸿蒙笔记2
    1.图片设置:1加载网络图片,申请权限。申请权限:entry-src-resources-module.json5 2加载本地图片 ,两种加载方式API鼠标悬停在Image, 点击showinAPIReference interpolation:看起来更加清晰   resource格式,读取本地资源文件这里,先按需求读取en_U......
  • 微信小程序关于小说类使用官方阅读器
    https://doc.weixin.qq.com/doc/w3_AAcAYAbdAFwpM63n1R5SIat3aa4cX?scode=AJEAIQdfAAoYHVCBbdAG4A1QYmAFQ上面是文档链接引入{"plugins":{"novel-plugin":{"version":"latest","provider":"wx293......
  • ssm微信小程序的图书管理系统
    摘要对图书管理的流程进行科学整理、归纳和功能的精简,通过软件工程的研究方法,结合当下流行的互联网技术,最终设计并实现了一个简单、易操作的图书管理小程序。内容包括系统的设计思路、系统模块和实现方法。系统使用过程主要涉及到管理员和用户两种角色,主要包含个人信息修......
  • [N-147]基于微信小程序电影院购票选座系统
    开发工具:IDEA、微信小程序服务器:Tomcat9.0,jdk1.8项目构建:maven数据库:mysql5.7前端技术:原生微信小程序+AdminLTE+vue.js服务端技术:springboot+mybatis本系统分微信小程序和管理后台两部分一、小程序功能:登录、注册、微信授权登录、首页、搜索电影、分类浏览电影信息、......
  • N-147基于微信小程序电影院购票选座系统
    开发工具:IDEA、微信小程序服务器:Tomcat9.0,jdk1.8项目构建:maven数据库:mysql5.7前端技术:原生微信小程序+AdminLTE+vue.js服务端技术:springboot+mybatis本系统分微信小程序和管理后台两部分一、小程序功能:登录、注册、微信授权登录、首页、搜索电影、分类浏览电影信息、......
  • (N-147)基于微信小程序电影院购票选座系统
    开发工具:IDEA、微信小程序服务器:Tomcat9.0,jdk1.8项目构建:maven数据库:mysql5.7前端技术:原生微信小程序+AdminLTE+vue.js服务端技术:springboot+mybatis本系统分微信小程序和管理后台两部分一、小程序功能:登录、注册、微信授权登录、首页、搜索电影、分类浏览电影信息、......
  • 如何使用V免签+彩虹易支付个人支付对接支付宝、微信搭建安装流程记录
    这两天没事闲的折腾了下个人免签支付,我相信有很多小伙伴也有这个痛点!这里记录下安装流程,年纪大了以免下次重搭忘记!源码下载以后开始服务器安装,简单点就上宝塔或aapanel(宝塔海外版)!首先ssh登录服务器,然后sudo-i切换到root用户。我这里选择安装宝塔海外版aapanel(英文界面......
  • 【全开源】JAVA二手车交易二手车市场系统源码支持微信小程序+微信公众号+H5+APP_博纳
    二手车交易二手车市场系统源码微信小程序——买卖无忧,交易更便捷在日益繁荣的二手车市场中,寻找一个高效、可靠的交易平台成为了买卖双方共同的需求。为满足这一需求,我们推出了二手车交易二手车市场系统源码微信小程序,让买卖无忧,交易更便捷。这款微信小程序整合了丰富的二手车......
  • 一个简单的微信推送通知
    无意间看到这个息知蛮好的一个推送工具,使用起来比较简单方便。我们来到首页,点击立即登录出来一个二维码,扫描这个二维码提示登录成功,然后进入后台,点击这里提示没关注不能用,我们就扫一下关注一下关注好了就是这样了测试一下标题内容都填一下,然后立即推送。结果微信没有......
  • MybatisPlus多参数分页查询,黑马程序员SpringBoot3+Vue3教程第22集使用MP代替pagehelpe
    前言:视频来源1:黑马程序员SpringBoot3+Vue3全套视频教程,springboot+vue企业级全栈开发从基础、实战到面试一套通关视频来源2:黑马程序员最新MybatisPlus全套视频教程,4小时快速精通mybatis-plus框架创作理由:网上MP实现分页查询功能的帖子易读性太差,具体实现看下面。根据视频完成......