wx-auth-router

1.0.5 • Public • Published

一、npm包介绍

拓展微信小程序路由跳转,方便增加路由页面授权的检查(如:登录状态、用户权限等)

二、使用

1.安装

执行 npm i wx-auth-router,并构建 npm

2.初始化

在 app.js 文件中引入 wxAuthRouter,定义用于检查授权状态的方法(必须返回布尔值),定义用于授权检查未通过时执行的回调,在 onLaunch 生命周期函数内调用 wxAuthRouter.init(checkCallback, unAuthCallback)

// app.js
import wxAuthRouter from 'wx-auth-router'

App({
  onLaunch: function () {
    /**
     * @description: 挂载全局对象 wxAuth
     * @param {func} checkCallback 自定义的检查函数,返回 boolean
     * @param {func} unAuthCallback 自定义的检查未通过时的回调
     */
    wxAuthRouter.init(this.checkCallback, this.unAuthCallback)
  },

  /**
   * @description: 检查函数
   * @return {boolean} 检查是否通过
   */
  checkCallback () {
    // 仅为示例:当缓存中不存在openId时,判断未用户未登录,授权检查不通过
    const openId = wx.getStorageSync('openId')
    return Boolean(openId)
  },

  /**
   * @description: 检查未通过时的回调
   * @param {string} url 检查未通过时,会返回当前要跳转的 url
   */
  unAuthCallback (url) {
    // 仅为示例:除了首页,其它页面的访问都需要登录
    if (url !== '/pages/index/index') {
      wx.navigateTo({
        url: '/pages/login/login',
      })
    }
  },
})

3.在页面内使用

wxAuth 全局对象提供两个API接口

(1) wxAuth.router( ) 页面跳转

// page.js

Page({
  // 仅为示例:跳转到未付款订单列表(需要登录)
  jumpOrderList () {
    // 使用授权路由跳转
    wxAuth.router({
      url: '/pages/orderList/orderList',
      type: 'navigateTo',
      params: {
        status: 'unpaid'
      }
    })
  }
})
参数 说明 类型 必填 默认值
url 目标页面路径 string -
type 页面跳转的类型,与微信小程序原生一致,包括:navigateTo, redirectTo, switchTab, reLaunch string navigateTo
params 页面参数 object -
success 接口调用成功的回调函数,与微信小程序原生一致 function -
fail 接口调用失败的回调函数,与微信小程序原生一致 function -
complete 接口调用结束的回调函数,与微信小程序原生一致 function -

(2) 授权检查 wxAuth.check( )
Promise 函数,检查通过时返回resolve(true);未通过时自动调用初始化时传入的回调,默认不返回reject(false)

// page.js

Page({
  // 仅为示例:商品详情页加入购物车(需要登录)
  async addToCart () {
    // 使用授权检查,通过时Promise状态为resolve
    const useReject = false
    await wxAuth.check(useReject)
    // 仅为示例:调用加入购物车接口
    await request({
      url: '/example/cart/add',
      data: ...
    })
  }
})
参数 说明 类型 必填 默认值
useReject 检查授权未通过时,是否返回Promise.reject,可用try catch 捕获 boolean false

Package Sidebar

Install

npm i wx-auth-router

Weekly Downloads

0

Version

1.0.5

License

ISC

Unpacked Size

8.9 kB

Total Files

5

Last publish

Collaborators

  • maikscat