api.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. import config from '../config';
  2. /**
  3. * 什么事情都不做
  4. */
  5. function noop() {}
  6. export function getCurrentWebview() {
  7. const pages = getCurrentPages();
  8. const page = pages[pages.length - 1];
  9. return page.$getAppWebview();
  10. }
  11. export function reject(reason) {
  12. return Promise.reject(reason);
  13. }
  14. export function resolve(data) {
  15. return Promise.resolve(data);
  16. }
  17. /**
  18. * 将 JSON 数据转换成 QueryString
  19. * @param {Object|Array} object 被转换的JSON数据
  20. * @param {String} [prefix=''] 键名前缀
  21. * @return {String}
  22. */
  23. export function qs(object, prefix = '') {
  24. if (Array.isArray(object)) {
  25. if (!prefix) {
  26. throw new Error('must given a not empty prefix');
  27. }
  28. return object.map(function (val) {
  29. if (val == null) return prefix + '[]=';
  30. switch(typeof val) {
  31. case 'boolean':
  32. return prefix + '[]=' + (val ? 1 : 0);
  33. case 'number':
  34. return prefix + '[]=' + val;
  35. case 'object':
  36. return qs(val, prefix + '[]');
  37. default:
  38. return prefix + '[]=' + encodeURIComponent(val);
  39. }
  40. }).join('&');
  41. }
  42. return Object.keys(object).map(function (prop) {
  43. const value = object[prop];
  44. const key = prefix ? `${prefix}[${prop}]` : prop;
  45. if (value == null) return key + '=';
  46. if (typeof value !== 'object') return key + '=' + encodeURIComponent(value);
  47. return qs(value, key);
  48. }).join('&');
  49. }
  50. /**
  51. * 页面跳转
  52. * @param {String} page 页面路径或网络地址
  53. * @param {Object|Function} params 页面跳转参数或接口调用结束的回调函数
  54. * @param {Function} [completion] 接口调用结束的回调函数(调用成功、失败都会执行)
  55. * @return {Promise}
  56. */
  57. export function jump(page, params, completion = noop) {
  58. let url = null;
  59. if (/^\/\//.test(page)) {
  60. page = 'http:' + page;
  61. }
  62. if (/^https?:\/\//i.test(page)) {
  63. url = page;
  64. page = 'pages/web/index';
  65. }
  66. if (url) {
  67. params = { url };
  68. }
  69. page = page.split(/\.+/).join('/');
  70. if (!/^\/?pages\//.test(page)) {
  71. page = '/pages/' + page.replace(/^\/+/, '');
  72. }
  73. const query = params ? qs(params) : null;
  74. return new Promise(function (resolve, reject) {
  75. var url= page + (query ? '?' + query : '');
  76. uni.navigateTo({
  77. url: url,
  78. });
  79. });
  80. }