故事背景
微信小程序确实给我吗提供了太多太多的API,好用白piao他不爽吗?但是伴随着高频率的使用,封装是大道必行~
简单明了上代码
公共方法卤煮统一放到utils/util.js中,上代码(干货)~
// 模态框
const showModal = (obj, callback) => {
const tempObj = obj || {};
const { cancelText = '取消', confirmText = '确定', cancelColor = '#999',
confirmColor = '#2f6ff8', content = '这是一个模态框', showCancel = true,
title = '提示' } = tempObj;
wx.showModal({
cancelColor,
cancelText,
complete: (res) => {},
confirmColor,
confirmText,
content,
fail: (res) => {},
showCancel,
title,
success: (result) => {
const { cancel } = result;
callback({ result: cancel ? 0 : 1 });
},
})
};
// 上传图片
const uploadImg = (obj, callback) => {
const tempObj = obj || {};
const {
count = 1,
sizeType = ['original', 'compressed'],
sourceType = ['album', 'camera'],
} = tempObj;
wx.chooseImage({
count,
sizeType,
sourceType,
success: (res) => {
const tempFilePaths = res.tempFilePaths;
callback({ imgPath: tempFilePaths });
},
fail: (err) => {
callback({ err});
},
});
};
module.exports = {
showModal,
uploadImg
}
然后在组件内采用相对路径拿具体的方法就可以了
import { showModal, uploadImg} from '相对路径'; // 引用方法1
var util = require('相对路径'); // 引用方法2,这样util暴露的方法都能拿到
一直在这找相对路径有点烦,所以卤煮采用了别的方法,微信小程序提供了app.js这个全局的js,而且里面的方法变量等在组件内都可以用getApp()拿到,所以卤煮把util封装的方法全部挂载到了全局app上面了,上代码~
//app.js
var util = require('./utils/util.js');
App({
globalData: {
userInfo: null
},
globalMethods: {
...util
},
})
所以在具体的组件内var { globalMethods } = getApp();
拿到全局的方法,用哪个调就完了~
本文地址:https://blog.csdn.net/yman_pro/article/details/107547657
您可能感兴趣的文章:
如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!
网友评论