Taro小程序路由跳转二次封装

Taro小程序路由跳转

import Taro from '@tarojs/taro'


// 打开新页面并跳转
function navigateTo (url, params) {
  const paramsStr = handleParams(params)
  Taro.navigateTo({
    url: url + paramsStr
  })
}

// 关闭当前页面并跳转新的页面
function redirectTo (url, params) {
  const paramsStr = handleParams(params)
  Taro.redirectTo({
    url: url + paramsStr
  })
}

// 返回上级页面
function navBack (delta) {
  let currentDelta = delta
  if (!delta || typeof delta !== 'number') {
    currentDelta = 1
  }
  Taro.navigateBack({delta: currentDelta}).then(r => r)
 }
 
// 关闭所有页面并跳转到tabBar页面
function switchTab (url, params) {
  const paramsStr = handleParams(params)
  Taro.switchTab({
    url: url + paramsStr
  }).then(r => r)
}

// 参数转换拼接
function handleParams (params) {
  let paramsStr = ''
  if (params && typeof params === 'object') {
    const keys = Object.keys(params) || []
    if (keys && keys.length) {
      keys.forEach((key, index) => {
        // paramsStr =
        if (index === 0) {
          paramsStr += `?${key}=${params[key]}`
        } else {
          paramsStr += `&${key}=${params[key]}`
        }
      })
    }
  }
  return paramsStr
}

export {
  navigateTo,
  redirectTo,
  navBack,
  switchTab,
  handleParams
}
上一篇:Taro小程序分享好友和朋友圈功能


下一篇:Taro小程序分享功能