index.js 1.56 KB
const routerPath = {
  index: '/pages/index/index',

  expCommon: '/pages/exp-common/exp-common',
  expBus: '/pages/exp-bus/exp-bus',
  expForm: '/pages/exp-form/exp-form',
  article: '/pages/artcle/article',

  example: '/pages/example/example',
  more: '/pages/more/more',
}

function parse(data) {
  let tempArr = [];
  for (let key in data) {
    tempArr.push(key + '=' + encodeURIComponent(data[key]));
  }
  return tempArr.join('&');
}

function push(path, option = {}) {
  if (typeof path == 'string') {
    option.path = path; //兼容无参数路径
  } else {
    if (path.name) {
      path.path = path.name;
    }
    option = path;
  }
  // console.log("option:", option);
  // 配置key值找到对应path
  let url = routerPath[option.path] || routerPath['index'];
  // console.log("url:", url);
  // 读取传入的配置参数
  let {
    query = {}, openType = 'navigate', duration = 0
  } = option;
  // json 转换为 字符串拼接参数
  let params = parse(query)
  // console.log("params:", params);
  if (params) {
    url = url + '?' + params;
  }
  // 是否需要延时跳转
  duration ? setTimeout(() => {
    to(openType, url);
  }, duration) : to(openType, url);
}

function to(openType, url) {
  let obj = {
    url
  };

  if (openType == 'redirect') {
    my.redirectTo(obj);
  } else if (openType == 'reLaunch') {
    my.reLaunch(obj);
  } else if (openType == 'switchTab') {
    my.switchTab(obj);
  } else if (openType == 'back') {
    my.navigateBack({
      delta: 1
    });
  } else {
    my.navigateTo(obj);
  }
}

module.exports = {
  parse,
  push,
  to
}