小程序路由小工具
发布于 3 年前 作者 tangyong 1122 次浏览 来自 分享

来由:由于微信小程序的路由跳转,传参写法不太友好,如果想直接传个对象过去还要转成字符串的形式,而且大小也有限制

功能:

  • 支持原生小程序方式跳转
  • 支持对象形式传参

路由跳转传参:

Route.navigateTo('../page/page',{name:'jslin',sex:'man',age:'18'})

获取参数:(阅后即焚,使用完将清空 params)

const params =  Route.params

相关代码:

/**
 * 路由工具,解决传参过多,支持对象形式传参
 * 用法:
 * 路由跳转
 * import Route from '../../utils/route'
 * Route.navigateTo('../page/page',{name:'jslin',sex:'man',age:'18'})
 * 
 * 路由参数获取
 * 阅后即焚 使用完,将清空 Route.params
 *  const params =  Route.params
 */

let _params = {}

class Route {

  constructor() {

    this.params = {}

    Object.defineProperty(this, 'params', {
      get() {
        const _params_ = _params
        this.removeParams()
        return _params_
      },
      set(v) {
        _params = v
      }

    })

  }

  navigateTo(url, params) {
    return new Promise((revose, reject) => {
      this.params = params
      wx.navigateTo({
        url,
        success: () => revose(),
        fail: (error) => reject(error)
      })
    })
  }

  redirectTo(url, params) {
    return new Promise((revose, reject) => {
      this.params = params
      wx.redirectTo({
        url,
        success: () => revose(),
        fail: (error) => reject(error)
      })
    })
  }

  reLaunch(url, params) {
    return new Promise((revose, reject) => {
      this.params = params
      wx.reLaunch({
        url,
        success: () => revose(),
        fail: (error) => reject(error)
      })
    })
  }

  navigateBack(delta = 0) {
    return new Promise((revose, reject) => {
      wx.navigateBack({
        delta,
        success: () => revose(),
        fail: (error) => reject(error)
      })
    })
  }

  switchTab(url, params) {
    return new Promise((revose, reject) => {
      this.params = params
      wx.switchTab({
        url,
        success: () => revose(),
        fail: (error) => reject(error)
      })
    })
  }

  removeParams() {
    this.params = {}
    _params = {}
  }

}

export default new Route()
回到顶部