uni-app applet non-sensing login logic implementation

  1. Encapsulation request, here is just a demo

    // request.js
    function post(url,data) {
          
          
      return new Promise((resolve, reject) => {
          
          
        uni.request({
          
          
          url,
          data,
          success: res => {
          
          
            if (res.code === 99) {
          
          
    			// 登录过期
              // 跳转到首页
              uni.reLaunch({
          
          URL: '/pages/index/index'})
            } else {
          
          
              resolve(res)
            }
          }
        })
      })
    }
    
  2. Package login interface (demo)

    // login.js
    export async function myLogin() {
          
          
      return new Promise(() => {
          
          
        uni.login({
          
          
          code,
          success: res => {
          
          
            // 调服务端登录
            const result = await post('/login', {
          
          code: res.code})
         		// 登录后把token存到本地缓存
            uni.setStorageSync('token', result.token)
            // 更新vuex中的登录状态
            store.commit('setIsLogin', true)
            resolve(result)
          }
        })
      })
    }
    
  3. transfer

    // App.vue
    onLaunch() {
          
          
      this.init()
    },
    async init() {
          
          
      if (uni.getStorageSync('token')) {
          
          
        // 如果本地有token,不调登录,继续执行其他逻辑
      } else {
          
          
        // 调登录
      	await myLogin()
        init()
      }
    }
    // home.vue
    import {
          
           mapGetters } from 'vuex'
    export default {
          
          
    	computed: {
          
          
        ...mapGetters(['isLoginGetters']),
        isLogin() {
          
          
          return this.isLoginGetters
        }
      },
      watch: {
          
          
        // 由于小程序没有一套完善的路由机制,开发者无法拦截小程序启动后进入页面的行为,可能会进入页面后,还没有拿到全局登录状态,所以需要监听
    	isLogin: {
          
          
    	  handler(newVal, oldVal) {
          
          
             if (newVal) {
          
          
              // 登录成功后再继续执行当前页面其他业务逻辑
             }
          },
          immediate: true
       }
     }
    }
    
  4. In most cases, entering the mini program is to go to the home page. If there are some pages in the applet that come directly from scanning the code or clicking the sharing card (such as the store details page), the above logic of monitoring the login status needs to be implemented.

  5. Requirements : Optimization of login expiration processing

    back to step 1

    uni.reLaunch({url: ‘/pages/index/index’})

    This code will jump to the home page under any circumstances, as long as the login expires. If you don’t want to jump, but continue to request the current page after re-login without feeling the current page, what should you do?

    Idea 1: Maintain an expired request queue in the encapsulated request method, and then take it out of the queue to call after re-login, but how to continue to execute the code after the request callback on the original page after the call?

    Idea 2: When the login expires, get the path and query parameters through uni.getLaunchOptionsSync(), and then pass it to the reLaunch method, but in this way, you need to judge whether the applet is normally clicked to jump to the current page, or entered by sharing or scanning the code, and there will be An action of jumping to the page, the experience is not good.

    Idea 3: Get the current page object through getCurrentPages() in the onLoad or onShow callback of the page to be processed, and put it in vuex, call the onLoad method of the page object when the login expires, and pass in the startup parameters, the code is as follows:

    // store/index.js
    state: {
          
          
      currentPage: null
    }
    mutations: {
          
          
      setCurrentPage(state, currentPage) {
          
          
        state.currentPage = currentPage
      }
    }
    // 店铺详情页面 /pages/store/index
    export default {
          
          
      methods: {
          
          
        ...mapMutations(['setCurrentPage']),
        onShow() {
          
          
          const pages = getCurrentPages()
          this.setCurrentPage(pages[pages.length - 1])
        }
      }
    }
    // request.js
    if (res.code === 99) {
          
          
      // 登录过期
      const launchOptions = uni.getLaunchOptionsSync()
      if (launchOptions.path === 'pages/store/index') {
          
          
        store.state.currentPage && store.state.currentPage.onLoad(launchOptions.query)
      } else {
          
          
        // 跳转到首页
      	uni.reLaunch({
          
          URL: '/pages/index/index'})
      }
    } else {
          
          
      resolve(res)
    }
    

    In this way, when the interface reports that the token has expired, no matter which page you are on (obtain getCurrentPages on the required page and save it to vuex), you can log in again without feeling, and continue the request logic of the page after successful login.

Guess you like

Origin blog.csdn.net/xinTianou123/article/details/126062883
Recommended