小程序 2
小程序常用接口(js中使用):
1. 定时器API: 多少毫秒后调用定时器中的代码
1 var time_name = setTimeout ( function ( ) { 2 3 执行代码 4 5 }, 毫秒) 6 7 time_name: 定时器名称。在清除定时器时需要用到 8 9 clearTimeOut(time_name) : 清除定时器
2. 路由API
1 #a. 关闭当前页面,跳转到应用内的某个页面(不允许跳转到tabbar页面) 2 3 wx.redirectTo ( { url: "..." }) 4 5 #b. 保留当前页面,跳转到某个页面(不能跳转到tabbar页) 6 7 wx.navigateTo( { url:“...”} ) 8 9 #c. 关闭当前页面。返回上一页面或多级页面 10 11 console.log( '当前的页面栈',getCurrentPages() ) 12 13 wx.navigateBack( { delta:返回级数} ) 14 15 #d. 跳转到tabBar页面,关闭其他所有非tabBar页面 16 17 wx.switchTab( { url:"..." } ) 18 19 #e. 关闭所有页面,打开到应用内的某个页面 20 21 wx.reLaunch( { url:“...”} ) 22 23
3. 消息提示框
a. 显示消息提示框 wx.showToast ( { title:‘成功’ ,icon:‘success’,duration:2000} ) b. 显示模态对话框 wx.showModal( { title:‘提示’, content:‘这是一个模态弹窗’, success(res){ if(res.confirm){ console.log(‘用户点击确定’) }else if (res.cancel){ console.log(‘用户点击取消’) } } } ) c. 显示操作菜单 wx.showActionSheet( { itemList:[‘A’,‘B’,‘C’], success(res){ console.log(res.tapIndex) #tapindex:用户点击的按钮序号,从0开始 }, fail(res){ console.log(res.errMsg) } } )
4. 网络请求
a. 发起请求 wx.request({ url:“”, method:", data:{ ... }, header:{ ‘content-type’:... }, success(res){ ‘...’ } }) b. 下载请求 wx.downloadfile({ url:“”, header:“”, filePath:“”, # 文件下载后的存储路径,不写时自动保存到临时文件路径tempFilePath下. success(res){ if(res.statusCode== 200){ wx.saveFile({ tempFilePath:res.tempFilePath, success:function(res){ 。。。 } }) } } })
5. 数据缓存
1 a. 将数据存储在缓存中 2 3 wx.setStorage ( { key:“key”,data:“value” } ) 4 5 b. 通过‘键’取出缓存中的数据 6 7 wx.getStorage ( { key:“key”,success(res){ console.log(res.data)} } )
6. 位置
1 a. 使用微信内置地图查看当前位置
2
3 wx.getLocation( { # 获取当前位置(经纬度等)
4
5 type:‘gcj02’,
6
7 success(res){
8
9 const latitude = res . latitude
10
11 const longitude = res.longitude
12
13 wx.openLocation({ # 打开微信内置地图
14
15 latitude,
16
17 longitude,
18
19 scale:18
20
21 })
22
23 }
24
25 } )
26
27 b. 打开地图选择位置
28
29 wx.chooseLocation( {
30
31 success(res){
32
33 console.log(res)
34
35 }
36
37 } )
38
39 c. 使用第三方地图(腾讯地图)
40 // 获取用户当前(省、市、县区)位置
41 getLocation: function () { # 自定义函数
42 var that = this;
43 wx.getLocation({ # 先获取当前的经纬度坐标
44 success: function (res) {
45 let latitude = res.latitude;
46 let longitude = res.longitude;
47 wx.request({ # 发送请求到腾讯地图(首先注册腾讯地图账号,生成key,绑定此小程序)
48 url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${app.globalData.tencentMapKey}`,
49 success: res => {
50 that.setData({
51 "region[0]": res.data.result.ad_info.province, //省
52 "region[1]": res.data.result.ad_info.city, //市
53 "region[2]": res.data.result.ad_info.district //县区
54 });
55 }
56 })
57 },
58 })
59 }

浙公网安备 33010602011771号