以下是将20个微信小程序常用方法封装到utils.js中并暴露给外部使用的示例代码
function getCurrentPageUrl() {
const pages = getCurrentPages();
const currentPage = pages[pages.length - 1];
const url = `/${currentPage.route}`;
return url;
}
function getCurrentPageOptions() {
const pages = getCurrentPages();
const currentPage = pages[pages.length - 1];
const options = currentPage.options;
return options;
}
function showSuccessToast(msg) {
wx.showToast({
title: msg,
icon: 'success',
duration: 1500
});
}
function showErrorToast(msg) {
wx.showToast({
title: msg,
icon: 'none',
duration: 1500
});
}
function showModal(title, content, confirmText = '确定', cancelText = '取消') {
return new Promise((resolve, reject) => {
wx.showModal({
title: title,
content: content,
confirmText: confirmText,
cancelText: cancelText,
success(res) {
if (res.confirm) {
resolve(true);
} else if (res.cancel) {
resolve(false);
}
},
fail(err) {
reject(err);
}
});
});
}
function getElementInfo(selector, context = null) {
return new Promise((resolve, reject) => {
const query = context ? wx.createSelectorQuery().in(context) : wx.createSelectorQuery();
query.select(selector).boundingClientRect(res => {
if (res) {
resolve(res);
} else {
reject(new Error(`找不到元素:${selector}`));
}
}).exec();
});
}
function throttle(fn, interval = 300) {
let timer = null;
return function (...args) {
if (!timer) {
timer = setTimeout(() => {
fn.apply(this, args);
timer = null;
}, interval);
}
};
}
function debounce(fn, delay = 500) {
let timer = null;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, args);
}, delay);
};
}
function getSystemInfo() {
return new Promise((resolve, reject) => {
wx.getSystemInfo({
success(res) {
resolve(res);
},
fail(err) {
reject(err);
}
});
});
}
function getNetworkType() {
return new Promise((resolve, reject) => {
wx.getNetworkType({
success(res) {
resolve(res.networkType);
},
fail(err) {
reject(err);
}
});
});
}
function setNavigationBarTitle(title) {
return new Promise((resolve, reject) => {
wx.setNavigationBarTitle({
title: title,
success() {
resolve();
},
fail(err) {
reject(err);
}
});
});
}
function setNavigationBarColor(frontColor, backgroundColor) {
return new Promise((resolve, reject) => {
wx.setNavigationBarColor({
frontColor: frontColor,
backgroundColor: backgroundColor,
success() {
resolve();
},
fail(err) {
reject(err);
}
});
});
}
function getSetting() {
return new Promise((resolve, reject) => {
wx.getSetting({
success(res) {
resolve(res.authSetting);
},
fail(err) {
reject(err);
}
});
});
}
function openSetting() {
return new Promise((resolve, reject) => {
wx.openSetting({
success(res) {
resolve(res.authSetting);
},
fail(err) {
reject(err);
}
});
});
}
function getUserInfo(withCredentials = false) {
return new Promise((resolve, reject) => {
wx.getUserInfo({
withCredentials: withCredentials,
success(res) {
resolve(res.userInfo);
},