微信小程序开发常用API及功能详解

1. 网络请求

wx.request

发起网络请求,类似于AJAX。

wx.request({
  url: 'https://api.example.com/data',
  method: 'GET',
  data: {
    key: 'value'
  },
  success(res) {
    console.log(res.data)
  },
  fail(err) {
    console.error(err)
  },
  complete() {
    console.log('请求完成')
  }
})

wx.uploadFile 和 wx.downloadFile

文件上传和下载。

// 上传文件
wx.chooseImage({
  success(res) {
    const tempFilePaths = res.tempFilePaths
    wx.uploadFile({
      url: 'https://example.com/upload',
      filePath: tempFilePaths[0],
      name: 'file',
      success(res) {
        console.log(res.data)
      }
    })
  }
})

// 下载文件
wx.downloadFile({
  url: 'https://example.com/image.jpg',
  success(res) {
    wx.saveImageToPhotosAlbum({
      filePath: res.tempFilePath
    })
  }
})

2. 数据缓存

wx.setStorage 和 wx.getStorage

本地数据存储与读取。

// 异步存储
wx.setStorage({
  key: 'userInfo',
  data: {name: '张三', age: 25},
  success() {
    console.log('存储成功')
  }
})

// 异步读取
wx.getStorage({
  key: 'userInfo',
  success(res) {
    console.log(res.data)
  }
})

// 同步版本
try {
  wx.setStorageSync('userInfo', {name: '张三', age: 25})
  const data = wx.getStorageSync('userInfo')
  console.log(data)
} catch (e) {
  console.error(e)
}

3. 界面交互

wx.showToast 和 wx.showModal

显示提示框和模态对话框。

// 显示提示
wx.showToast({
  title: '操作成功',
  icon: 'success',
  duration: 2000
})

// 显示模态对话框
wx.showModal({
  title: '提示',
  content: '确定要删除吗?',
  success(res) {
    if (res.confirm) {
      console.log('用户点击确定')
    } else if (res.cancel) {
      console.log('用户点击取消')
    }
  }
})

wx.showLoading 和 wx.hideLoading

显示和隐藏加载提示。

wx.showLoading({
  title: '加载中...',
  mask: true
})

// 模拟异步操作
setTimeout(() => {
  wx.hideLoading()
}, 2000)

4. 路由导航

wx.navigateTo 和 wx.redirectTo

页面跳转。

// 保留当前页面,跳转到新页面(跳转到非tabbar页面)
wx.navigateTo({
  url: '/pages/detail/detail?id=123'
})

//detail?id=123  这个是页面之间传递参数的方式

// 关闭当前页面,跳转到新页面
wx.redirectTo({
  url: '/pages/login/login'
})

// 返回上一页
wx.navigateBack({
  delta: 1  // 返回的页面数
})

//跳转到tabbar页面
wx.switchTab({
url: '/pages/detail/detail'

})

5. 设备相关

wx.getSystemInfo

获取系统信息。

wx.getSystemInfo({
  success(res) {
    console.log(res.model) // 手机型号
    console.log(res.pixelRatio) // 设备像素比
    console.log(res.windowWidth) // 窗口宽度
    console.log(res.system) // 操作系统版本
  }
})

wx.makePhoneCall

拨打电话。

wx.makePhoneCall({
  phoneNumber: '10086'
})

6. 位置相关

wx.getLocation

获取当前位置。

wx.getLocation({
  type: 'wgs84',
  success(res) {
    const latitude = res.latitude
    const longitude = res.longitude
    console.log(latitude, longitude)
  },
  fail() {
    wx.showToast({
      title: '获取位置失败',
      icon: 'none'
    })
  }
})

wx.chooseLocation

打开地图选择位置。

wx.chooseLocation({
  success(res) {
    console.log(res.name) // 位置名称
    console.log(res.address) // 详细地址
    console.log(res.latitude, res.longitude) // 经纬度
  }
})

7. 媒体相关

wx.chooseImage 和 wx.previewImage

选择图片和预览图片。

// 选择图片
wx.chooseImage({
  count: 3, // 最多选择3张
  sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图
  sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机
  success(res) {
    const tempFilePaths = res.tempFilePaths
    // 预览图片
    wx.previewImage({
      current: tempFilePaths[0], // 当前显示图片的http链接
      urls: tempFilePaths // 需要预览的图片http链接列表
    })
  }
})

wx.chooseVideo

选择视频。

wx.chooseVideo({
  sourceType: ['album', 'camera'],
  maxDuration: 60,
  camera: 'back',
  success(res) {
    console.log(res.tempFilePath)
  }
})

8. 支付相关

wx.requestPayment

发起微信支付。

wx.requestPayment({
  timeStamp: '1414561699',
  nonceStr: '5K8264ILTKCH16CQ2502SI8ZNMTM67VS',
  package: 'prepay_id=wx201410272009395522657a690389285100',
  signType: 'MD5',
  paySign: 'C380BEC2BFD727A4B6845133519F3AD6',
  success(res) {
    console.log('支付成功')
  },
  fail(res) {
    console.log('支付失败', res)
  }
})

9. 数据统计

wx.reportAnalytics

自定义数据上报。

wx.reportAnalytics('purchase', {
  price: 120,
  color: 'red'
})

10. 开放接口

wx.login 和 wx.getUserInfo

登录和获取用户信息。

// 登录
wx.login({
  success(res) {
    if (res.code) {
      // 发送 res.code 到后台换取 openId, sessionKey, unionId
      console.log('登录成功', res.code)
    }
  }
})

// 获取用户信息
wx.getUserProfile({
  desc: '用于完善会员资料',
  success(res) {
    console.log('用户信息', res.userInfo)
  }
})

11. 画布相关

wx.createCanvasContext

创建画布上下文。

const ctx = wx.createCanvasContext('myCanvas')

ctx.setFillStyle('red')
ctx.fillRect(10, 10, 150, 75)
ctx.draw()

12. 动画

wx.createAnimation

创建动画。

const animation = wx.createAnimation({
  duration: 1000,
  timingFunction: 'ease',
})

this.animation = animation

animation.scale(2, 2).rotate(45).step()
animation.scale(1, 1).rotate(0).step()

this.setData({
  animationData: animation.export()
})

13. 扫码

wx.scanCode

调起客户端扫码界面。

wx.scanCode({
  success(res) {
    console.log(res.result)
  },
  fail(res) {
    console.log('扫码失败', res)
  }
})

14. 分享

onShareAppMessage

自定义转发内容。

// 在Page中定义
onShareAppMessage() {
  return {
    title: '自定义转发标题',
    path: '/page/user?id=123',
    imageUrl: '/images/share.jpg'
  }
}

以上是微信小程序开发中最常用的一些API,涵盖了基础功能、网络请求、界面交互、设备能力、媒体处理等多个方面。实际开发中,根据具体需求选择合适的API组合使用,可以高效地实现各种功能。

小程序API还在不断更新中,建议定期查看,微信官方文档https://developers.weixin.qq.com/miniprogram/dev/api/获取最新信息。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@程序员ALMJ

打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值