router.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. const pages = {
  2. home: '/pages/index/index',
  3. adjust: '/pages/adjust/index',
  4. detail:'/pages/detail/index',
  5. auth:'/pages/auth/index',
  6. search:'/pages/search/index',
  7. projectlist:'/pages/projectlist/index',
  8. usercenter:'/pages/usercenter/index',
  9. feedback:'/pages/feedback/index',
  10. spacelist:'/pages/spacelist/index',
  11. search:'/pages/search/index',
  12. adjustlog:'/pages/adjustlog/index',
  13. spacelog:'/pages/spacelog/index',
  14. }
  15. function to(page, data) {
  16. if (!pages[page]) { throw new Error(`${page} is not exist!`) }
  17. const _result = []
  18. for (const key in data) {
  19. const value = data[key]
  20. if (['', undefined, null].includes(value)) {
  21. continue
  22. }
  23. if (value.constructor === Array) {
  24. value.forEach(_value => {
  25. _result.push(encodeURIComponent(key) + '[]=' + encodeURIComponent(_value))
  26. })
  27. } else {
  28. _result.push(encodeURIComponent(key) + '=' + encodeURIComponent(value))
  29. }
  30. }
  31. const url = pages[page] + (_result.length ? `?${_result.join('&')}` : '')
  32. return url
  33. }
  34. class Router {
  35. push(page, param = {}, events = {}, callback = () => {}) {
  36. wx.navigateTo({
  37. url: to(page, param),
  38. events,
  39. success: callback
  40. })
  41. }
  42. pop(delta) {
  43. wx.navigateBack({ delta })
  44. }
  45. redirectTo(page, param) {
  46. wx.redirectTo({ url: to(page, param) })
  47. }
  48. reLaunch() {
  49. wx.reLaunch({ url: pages.home })
  50. }
  51. toHome() {
  52. this.reLaunch()
  53. // if (getCurrentPages().length > 1) { this.pop() } else { this.reLaunch() }
  54. }
  55. }
  56. export default new Router()