微信小程序 跳转页面 页面栈层数限制,如果继续使用navigateTo会报错,所以统一处理,报错了就用redirectTo
const jump = (to) => {
let options = {};
let url = '';
if (typeof to === 'object') {
url = to.path;
if (to.params) {
url = addParams(url, to.params);
}
} else if (typeof to === 'string') {
let index = to.indexOf('?');
if (index !== -1) {
url = addParams(to.substring(0, index), getParams(to));
} else {
url = to;
}
}
options = {
url: url,
fail: (res) => {
console.log(res);
if (res.errMsg === 'navigateTo:fail webview count limit exceed') {
redirectTo(to);
}
}
}
let pages = getCurrentPages();
let curPage = pages[pages.length - 1];
if (options.url.substring(1) !== curPage.route) {
wx.navigateTo(options);
}
}
const back = (popIndex) => {
let delta = 1;
if (popIndex) {
delta = popIndex;
}
wx.navigateBack({
delta: delta
});
}
const redirectTo = (to) => {
let options = {};
let url = '';
if (typeof to === 'object') {
url = to.path;
if (to.params) {
url = addParams(url, to.params);
}
} else if (typeof to === 'string') {
let index = to.indexOf('?');
if (index !== -1) {
url = addParams(to.substring(0, index), getParams(to));
} else {
url = to;
}
}
options = {
url: url
};
let pages = getCurrentPages();
let curPage = pages[pages.length - 1];
if (options.url.substring(1) !== curPage.route) {
wx.redirectTo(options);
}
}
const getParams = (url) => {
let params = {};
if (!url || !url.trim()) {
return params;
}
if (url.indexOf('?') < 0) {
return params;
}
let queryStr = url.substring(url.indexOf('?') + 1);
if (queryStr.indexOf('&') < 0) {
let map = queryStr.split('=');
let key = map[0];
params[key] = map[1];
} else {
queryStr.split('&').forEach((item) => {
let map = item.split('=');
let key = map[0];
params[key] = map[1];
})
}
return params;
}
const addParams = (url, params) => {
let kvArr = [];
for (let key in params) {
if (key) {
kvArr.push(key + '=' + params[key]);
}
}
return url.indexOf('?') < 0 ? url + '?' + kvArr.join('&') : url + '&' + kvArr.join('&');
}
module.exports = {
jump: jump,
back: back,
redirectTo: redirectTo
}