微信小程序代码片段

代码片段记录

下拉刷新

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
onPullDownRefresh:function() {
// 监听该页面用户下拉刷新事件
// 可以在触发时发起请求,请求成功后调用wx.stopPullDownRefresh()来结束下拉刷新
var that = this;
console.log('下拉拉拉')
wx.showNavigationBarLoading();//在当前页面显示导航条加载动画
//wx.startPullDownRefresh();
wx.hideNavigationBarLoading();//隐藏导航条加载动画。
wx.stopPullDownRefresh();//停止当前页面下拉刷新。
that.setData({
homeDataList: [],
pageIndex: 1,
showEndTxt: false
})
common.checkThreeRdSessionTimeOut(that);
},

上拉加载

1
2
3
4
5
//滑动至底部加载更多
onReachBottom:function(e){
var that = this;
that.loadMoreModuleData();
},

接口请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
checkSession:function(){
var that = this;
const requestTask = wx.request({
url: that.globalData.h5Request + 'miniApp/checkSessionTimeOut',
data: {//请求的参数
ThreeRdSessionId: wx.getStorageSync('threeRdSessionId')
},
success: function (res) {
wx.hideLoading();
if(res.data=='1'){
that.getUserInfo();//获取用户信息
}else{
if (getCurrentPages().length != 0) {//重新加载首页
getCurrentPages()[getCurrentPages().length - 1].onShow();
var e = getCurrentPages()[getCurrentPages().length - 1]
if (e.data.reloadData!=undefined && e.data.reloadData != 1) {
e.data.reloadData = 0;
getCurrentPages()[getCurrentPages().length - 1].loadData()
}
}
}
}
})
//监听 HTTP Response Header 事件。会比请求完成事件更早
//lambda表达式用的是 () => {}
requestTask.onHeadersReceived((res) => {
console.log("onHeadersReceived", res)
})
},

接口请求,抽取

app.js中公共数据设置全局的URL前缀

1
2
3
4
5
6
globalData: {
userInfo: null,
isIphonex: false,
h5Request: 'https://ldyh5.dolphin-free.com/',//上传接口
supportRequest: 'http://api.nnzhp.cn/' //普通接口
},

自定义请求函数(公用)/utils/request.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/**
* 自定义请求函数
* @params {String} url 请求路径
* @params {Object} data 请求数据
* @params {String} method 请求方式
* @params {Number} flag 是否缓存token的标志 0:否,1:是
*
*/
module.exports = function request(url, data, method, flag = 0, that = getApp()) {
console.log(url,1111)
const host = that.globalData.supportRequest
let token = wx.getStorageSync(that.storageKeys.TOKEN) || ''

return new Promise((resolve, reject) => {
wx.showLoading({
title: '加载中',
})
//网络请求
wx.request({
url: host + url,
data: data,
method: method,
dataType: 'json',
header: {
// 'content-type': 'application/json; charset=UTF-8', // 按json格式请求
'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',//按表单形式请求
'Authorization': token
},
success: function(res) { //服务器返回数据
console.log(url)
console.log(res)
// console.log(res.header)
if (flag == 1) { // 更新缓存token
wx.setStorageSync(that.storageKeys.TOKEN, res.header.Authorization);
}
if (res.statusCode == 200) {
//响应码 0表示成功, <0 表示失败,>0表示警告
if (res.data.errCode === 0) {
resolve(res.data.data);
} else {
reject(res.data)
}
} else if (res.statusCode === 502) {
wx.showToast({
title: '服务器更新',
icon: 'none'
})
} else if (res.statusCode === 500) {

wx.showToast({
title: res.data.errMsg || "接口异常",
icon: 'none',
duration: 1500,
})
} else if (res.statusCode === 403) {
reject(res.data)
} else { //返回错误提示信息
setTimeout(() => {
wx.showToast({
title: res.data.errMsg || "主人,我出错啦o(╥﹏╥)o",
icon: 'none',
duration: 1500,
})
}, 500)
reject(res.data)
}
wx.hideLoading()
},
fail: function(e) {
wx.hideLoading();
console.log(e)
reject({errMsg:"接口调用失败"})
},
})
})
}

调用:get、post、上传(选文件)、下载

各个页面对应的api js common/api/home-api.js

1
2
3
4
5
6
7
8
9
10
11
const httpRequest = require('../../utils/request')

//get请求
export function getSomething(options) {
return httpRequest('api/user/stu_info', options, 'GET')
}

//post请求
export function postSomething(options) {
return httpRequest('api/user/login', options, 'POST')
}

调用的地方 pages/home/home.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
Page({
/**
* 页面的初始数据
*/
data: {
login:{
username:"niuhanyang",
passwd:"aA123456",
},
imgUrl: "https://res.wx.qq.com/wxdoc/dist/assets/img/0.4cb08bb4.jpg",
//...
},

/**
* get请求数据
*/
getSomething: function(){
homeApi.getSomething().then(res =>{
getApp().toastNone(res)
}).catch(err => {
getApp().toastNone(err)
});
},
/**
* post请求数据
*/
postSomething: function(){
let that = this;
homeApi.postSomething(that.data.login).then(res =>{
getApp().toastNone(res)
}).catch(err =>{
getApp().toastNone(err)
});
},


/**
* 上传
*/
gotoShowIdCart: function(e){
var that = this;
var dataType = e.currentTarget.dataset.datatype;
debugger
wx.chooseImage({
count: 1, // 最多可以选择的图片张数,默认9
sizeType: ['original', 'compressed'], // original 原图,compressed 压缩图,默认二者都有
sourceType: ['album', 'camera'], // album 从相册选图,camera 使用相机,默认二者都有
success: function (res) {
wx.showLoading({ title: '上传中', });

that.setData({
isUploadPic: 1
})
console.log(res)
var tempFilePaths = res.tempFilePaths
wx.saveFile({
tempFilePath: tempFilePaths[0],
success: function (res) {
var savedFilePath = res.savedFilePath
wx.uploadFile({
url: requesth5 + 'miniApp/uploadLogImg', //仅为示例,非真实的接口地址
filePath: savedFilePath,
name: 'file',
formData: {
TmallShopId: that.data.tmallShopId,
ThreeRdSessionId: that.data.threeRdSessionId,
filePath: savedFilePath, // 要上传文件资源的路径
}, // HTTP 请求中其他额外的参数
success: function (res) {
if (res.statusCode == 200) {
var obj = JSON.parse(res.data);;
// var data = res.data
if (dataType == '1') {
that.setData({
cardPositivePic: obj.picUrl,
hideidcard1: false
})
} else if (dataType == '2') {
that.setData({
cardNativePic: obj.picUrl,
hideidcard2: false
})
}
wx.hideLoading();
that.setData({
isUploadPic: 0
})
} else {
that.showToast(res.errMsg);
}
}
})

},
fail: function () {
console.log('fail')
}
})
},
fail: function () {

},
complete: function () {

}
})
},
/**
* 下载
*/
downUrl(e) {
let that = this;
console.log("保存文件")
console.log(this.data.imgUrl)
console.log(e)

if (!this.data.imgUrl) {
getApp().toastNone("没有相关文件:" + this.data.imgUrl)
return;
}

wx.showLoading({
title: '正在保存文件'
})
let finalSharePosterImg = this.data.imgUrl;
console.log("保存文件:" + finalSharePosterImg)
wx.downloadFile({
url: finalSharePosterImg,
success(fileinfo) {
let filePath = fileinfo.tempFilePath;
console.log("下载成功", fileinfo)
wx.openDocument({
filePath: filePath,
success: function(res) {
console.log('打开文档成功')
},
complete: function(coml) {
wx.hideLoading()
}
})
// wx.saveFile({
// tempFilePath: filePath,
// success: function(res) {
// console.log("保存成功",res)
// wx.hideLoading()
// // wx.showToast({
// // title: '已保存',
// // })
// that.setData({
// showMenu: false
// })
// console.log(res);
// },
// fail: function(res) {
// console.log(res)
// let errMsg = res.errMsg
// wx.getSetting({
// success(res) {
// if (!res.authSetting['scope.writePhotosAlbum']) {
// wx.showModal({
// title: '警告',
// content: '您未授权保存到相册,将无法正常保存文件',
// showCancel: false,
// success: function(res) {
// wx.hideLoading()
// if (res.confirm) {
// wx.openSetting({
// success: (res) => {

// }
// })
// }
// }
// })
// } else {
// wx.hideLoading()
// wx.showToast({
// title: '保存失败,请刷新重试。',
// icon: 'none'
// })
// that.setData({
// showMenu: false
// })
// }
// }
// })

// }
// })
},
fail(errinfo) {
wx.hideLoading()
wx.showToast({
title: '获取文件失败,请刷新重试.',
icon: 'none'
})
that.setData({
showMenu: false
})
}
})
}

})

展示页面(参考)/pages/home/home.wxml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<!--pages/home/home.wxml-->
<text style="background-color:#ff0000;">网络请求</text>

<view class="font50" catchtap="getSomething">普通get网络请求</view>
<view class="font50" catchtap="postSomething">普通post网络请求</view>

<view class='IdCard_Pic' >
<!-- 上传前 -->
<view class='item' wx:if="{{hideidcard1 == true}}" bindtap='gotoShowIdCart' data-dataType='1' name="upImg">
<view class='mask ud_layout_c2'>
<icon class='iconfont icon-xiangji'></icon>
<view class='font10 c999'>身份证正面照片</view>
</view>
</view>
<!-- end上传前 -->
<!-- 上传后 -->
<view class='item upload' wx:if="{{hideidcard1 == false}}" bindtap='gotoShowIdCart' data-dataType='1'>
<view class='mask lr_layout_c'>
<icon class='iconfont icon-xiangji'></icon>
</view>
<image src='{{cardPositivePic}}' mode='aspectFill'></image>

</view>
<!-- end上传后 -->
<!-- 上传前 -->
<view class='item' wx:if="{{hideidcard2 == true}}" bindtap='gotoShowIdCart' data-dataType='2'>
<view class='mask ud_layout_c2'>
<icon class='iconfont icon-xiangji'></icon>
<view class='font10 c999'>身份证反面照片</view>
</view>
</view>
<!-- end上传前 -->
<!-- 上传后 -->
<view class='item upload' wx:if="{{hideidcard2 == false}}" bindtap='gotoShowIdCart' data-dataType='2'>
<view class='mask lr_layout_c'>
<icon class='iconfont icon-xiangji'></icon>
</view>
<image src='{{cardNativePic}}' mode='aspectFill'></image>
</view>
<!-- end上传后 -->

</view>
<view class="font50" catchtap="downUrl">下载</view>

登录

wx.login 登录

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// 重新登录
wx.login({
success: function (res) {
var code = res.code;
if (code) {
wx.request({
url: that.globalData.h5Request + 'miniApp/wxLoginNew',
data: {
code: code,
threeRdSessionId: wx.getStorageSync('threeRdSessionId'),
unionId: wx.getStorageSync('unionid'),
easyChannelId: wx.getStorageSync('easyChannelId'), //商户独立绑定小程序改造 by wuwq
tmallShopId: wx.getStorageSync('tmallShopId'),
miniAppType: 4
},
success: function (res) {
wx.hideLoading();
var data = res.data;
if (isNaN(data.error)) {
wx.setStorageSync('threeRdSessionId', data.threeRdSessionId);
//是否显示加入购物车按钮:1 是 0 否
wx.setStorageSync('isShowCart', data.isShowCart);
//折扣标签设置:1 显示折扣标签 2显示降价金额 0 不显示
wx.setStorageSync('isShowDiscountTag', data.isShowDiscountTag);
//裂变小程序appId
wx.setStorageSync('marketingMiniAppId', data.marketingMiniAppId);
//综合版社交小程序appId
wx.setStorageSync('integrateMiniAppId', data.integrateMiniAppId);
wx.setStorageSync('miniAppSource', "13");
wx.setStorageSync('miniAppType', "4");
if (!isNaN(data.unionid) && data.unionid != "") {
wx.setStorageSync('unionid', data.unionid);
}

if (getCurrentPages().length != 0) {//重新加载首页
getCurrentPages()[getCurrentPages().length - 1].onShow()
var e = getCurrentPages()[getCurrentPages().length - 1]
if (e.data.reloadData != undefined && e.data.reloadData != 1) {//首页
e.data.reloadData = 0;
getCurrentPages()[getCurrentPages().length - 1].loadData()
}
}
}
}
})
} else {
console.log('获取用户登录态失败!' + res.errMsg)
}
}
})

wx.checkSession检查登录态是否过期

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
onLoad: function (options) {
var that = this;
// 每次进核对页面查一下缓存是否失效
that.checkSession();
//...
},
// 每次进页面查一下缓存是否失效
checkSession: function () {
var that = this;
wx.request({
url: h5Request + 'miniApp/checkSessionTimeOut',
data: {
ThreeRdSessionId: wx.getStorageSync('threeRdSessionId')
},
success: function (res) {
wx.hideLoading();
if (res.data == '1') {
app.getUserInfo();//获取用户信息
} else {

}
}
})
},

公共js,暴露接口,便于引用;支付

公共js common.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
//暴露接口,便于引用
module.exports = {
weixinPayOrder: weixinPayOrder,
showToast: showToast
}

//微信支付方法
function weixinPayOrder(tradeId) {
var threeRdSessionId = wx.getStorageSync("threeRdSessionId");
wx.request({
url: h5Request + '/miniApp/wixin/miniAppPayOrder',
data: {
ThreeRdSessionId: threeRdSessionId,
tradeId: tradeId,
miniAppType: 4,
easyChannelId: wx.getStorageSync("easyChannelId")
},
success: function (res) {
var ret = res.data.ret;
var obj = res.data;
if (ret == '0') {
wx.requestPayment({
//相关支付参数
timeStamp: obj.timeStamp,
nonceStr: obj.nonceStr,
'package': 'prepay_id=' + obj.prepay_id,
signType: obj.signType,
paySign: obj.paySign,
//小程序微信支付成功的回调通知
success: function (res) {
wx.navigateTo({
url: '../../package-trade/paySuccess/paySuccess?tradeId=' + tradeId,
})
},
fail: function (res) {
wx.redirectTo({
url: '../../package-trade/payOrder/payOrder?tradeId=' + tradeId,
})
}
})
} else if (ret == 'm_0'){ //支付金额为0
wx.navigateTo({
url: '../../package-trade/paySuccess/paySuccess?tradeId=' + tradeId,
})
}else {
wx.redirectTo({
url: '../../package-trade/payOrder/payOrder?tradeId=' + tradeId,
})
//失败
}
}
})
}

//浮层提示
function showToast(that, text) {
that.setData({
toastText: text
});
setTimeout(function () {
that.setData({
toastText: ''
});
}, 1000);
}

//调用common.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import common= require("../../../resources/js/common.js");

Page({
/** 页面初始数据 */
data:{

}

/**微信支付 */
wechatpay: function () {
var that = this;
var storeId = that.data.storeId;
var tradeId = that.data.tradeId;
var groupDetailId = that.data.groupDetailId;
common.showToast(that, "跳转微信支付");
common.weixinPayOrder(tradeId, groupDetailId); //微信支付
},
})

跳转到别的小程序

  1. 先在app.json中声明

    1
    2
    3
    4
    "navigateToMiniProgramAppIdList": [
    "wxc3b9875f7ef24e85",
    "wx30a359ec2fe37327"
    ],
  2. 在页面的js中,创建跳转方法

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    //打开其他指定的小程序
    jumpToOtherMiniApp:function(miniAppType,url) {
    var appid = "";
    if(miniAppType == 3) {//裂变
    appid = "wxc3b9875f7ef24e85";
    }else if(miniAppType == 1) {//购物
    appid = "wx30a359ec2fe37327";
    }else{
    return;
    }
    wx.navigateToMiniProgram({
    appId: appid,
    path: url,
    envVersion: 'release',// 打开正式版
    success(res) {
    // 打开成功
    },
    fail: function (err) {
    console.log(err);
    }
    });
    }

    js中调用跳转方法

    1
    2
    3
    //跳转购物导航版小程序
    url = "/pages/views/home/home"
    that.jumpToOtherMiniApp(1,url);

设置导航栏

单个导航栏背景色

那个页面的json文件中修改(如/pages/home/home.json

1
2
3
4
{
"navigationBarBackgroundColor": "#00ffff",
"usingComponents": {}
}

整个小程序的导航栏背景色

修改app.jsonwindow下的navigationBarBackgroundColor的值

js中动态修改标题名称

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
changeRangeType:function (e) {
var rangeType=e.currentTarget.dataset.rangeType;
var that=this;
that.setData({
nextPageIndex:1,
isEnd: false,
rangeType:rangeType,
list:[]
})
this.showAchivementRanking();
that.showRangeType();
wx.setNavigationBarTitle({
title: that.getNavigatoinBarTitleStr(rangeType),
})
},
getNavigatoinBarTitleStr:function(rangeType){
if (rangeType=='1') {
return "本月业绩排行"
} else if (rangeType == '3') {
return "发展会员数"
}
return "本月业绩排行"
}

缓存

权限

拍照

路由

redirectTo

navigateTo

swtichTab