微信小程序入门学习教程,从入门到精通,微信小程序核心 API 详解与案例(13)
以下是根据你提供的“微信小程序核心API”内容整理的详细知识点、语法说明、具体案例代码(含详细注释),以及综合性案例。
微信小程序核心 API 详解与案例
一、获取设备与系统信息
1. 获取窗口信息 wx.getWindowInfo()
作用:获取当前窗口信息(如窗口宽度、高度、状态栏高度等)。
语法:
const info = wx.getWindowInfo()
返回值:Object,包含 windowWidth、windowHeight、statusBarHeight 等字段。
案例:
// pages/index/index.js
Page({onLoad() {const windowInfo = wx.getWindowInfo();console.log('窗口宽度:', windowInfo.windowWidth);console.log('窗口高度:', windowInfo.windowHeight);console.log('状态栏高度:', windowInfo.statusBarHeight);}
});
2. 获取设备信息 wx.getSystemInfoSync()
/ wx.getSystemInfo()
作用:获取设备系统信息(如品牌、型号、系统版本、屏幕尺寸等)。
wx.getSystemInfoSync()
:同步方法,直接返回结果。wx.getSystemInfo()
:异步方法,需传入 success/fail 回调。
案例(同步):
Page({onLoad() {try {const systemInfo = wx.getSystemInfoSync();console.log('设备品牌:', systemInfo.brand);console.log('设备型号:', systemInfo.model);console.log('系统版本:', systemInfo.system);console.log('屏幕宽度:', systemInfo.screenWidth);console.log('屏幕高度:', systemInfo.screenHeight);} catch (e) {console.error('获取系统信息失败:', e);}}
});
案例(异步):
wx.getSystemInfo({success(res) {console.log('异步获取系统信息:', res);},fail(err) {console.error('获取失败:', err);}
});
3. 获取微信应用信息 wx.getAccountInfoSync()
作用:获取小程序账号信息(如 appId、版本号等)。
案例:
Page({onLoad() {const accountInfo = wx.getAccountInfoSync();console.log('小程序 appId:', accountInfo.miniProgram.appId);console.log('版本号:', accountInfo.miniProgram.version);console.log('环境:', accountInfo.miniProgram.envVersion); // develop / trial / release}
});
二、网络请求
1. 发送 HTTPS 请求 wx.request()
作用:发起 HTTPS 网络请求(GET/POST 等)。
注意:需在小程序管理后台配置合法域名。
语法:
wx.request({url: 'https://example.com/api/data',method: 'GET',data: { key: 'value' },header: { 'content-type': 'application/json' },success(res) { console.log(res.data); },fail(err) { console.error(err); }
});
案例(获取天气数据):
Page({data: { weather: null },onLoad() {wx.request({url: 'https://api.example.com/weather', // 替换为真实接口method: 'GET',data: { city: '北京' },header: {'Authorization': 'Bearer your_token_here'},success: (res) => {if (res.statusCode === 200) {this.setData({ weather: res.data });console.log('天气数据:', res.data);} else {wx.showToast({ title: '请求失败', icon: 'none' });}},fail: (err) => {console.error('网络请求失败:', err);wx.showToast({ title: '网络错误', icon: 'none' });}});}
});
2. 文件上传与下载
上传文件 wx.uploadFile()
案例:
wx.chooseImage({success(res) {const tempFilePath = res.tempFilePaths[0];wx.uploadFile({url: 'https://example.com/upload',filePath: tempFilePath,name: 'file', // 后端接收字段名formData: { userId: '123' },success(uploadRes) {if (uploadRes.statusCode === 200) {wx.showToast({ title: '上传成功' });console.log('服务器返回:', uploadRes.data);}},fail(err) {console.error('上传失败:', err);}});}
});
下载文件 wx.downloadFile()
案例:
wx.downloadFile({url: 'https://example.com/file.pdf',success(res) {if (res.statusCode === 200) {const filePath = res.tempFilePath;wx.openDocument({ filePath, success: () => console.log('打开成功') });}},fail(err) {console.error('下载失败:', err);}
});
三、路由与跳转
1. 小程序内页面跳转
wx.navigateTo()
:保留当前页面,跳转到新页面(最多10层)wx.redirectTo()
:关闭当前页面,跳转到新页面wx.switchTab()
:跳转到 tabBar 页面wx.navigateBack()
:返回上一页
案例:
// 跳转到详情页,携带参数
wx.navigateTo({url: '/pages/detail/detail?id=123&name=测试',success() {console.log('跳转成功');}
});// 返回上一页
wx.navigateBack({delta: 1 // 返回层数
});
2. 小程序应用间跳转 wx.navigateToMiniProgram()
案例:
wx.navigateToMiniProgram({appId: '目标小程序的 appId',path: 'pages/index/index?param=123',extraData: { from: 'sourceApp' },envVersion: 'release', // develop / trial / releasesuccess(res) {console.log('跳转成功');},fail(err) {console.error('跳转失败:', err);}
});
四、界面交互与反馈
1. 页面弹框
wx.showToast()
:显示轻提示wx.showModal()
:显示模态弹窗wx.showLoading()
/wx.hideLoading()
:显示/隐藏加载提示
案例:
// 轻提示
wx.showToast({title: '操作成功',icon: 'success',duration: 2000
});// 模态确认框
wx.showModal({title: '提示',content: '确定要删除吗?',success(res) {if (res.confirm) {console.log('用户点击确定');} else if (res.cancel) {console.log('用户点击取消');}}
});
2. 下拉刷新
需在页面 JSON 中开启 enablePullDownRefresh: true
,并在 JS 中监听 onPullDownRefresh
pages/index/index.json:
{"enablePullDownRefresh": true
}
pages/index/index.js:
Page({onPullDownRefresh() {console.log('触发下拉刷新');// 模拟数据刷新setTimeout(() => {wx.stopPullDownRefresh(); // 停止刷新动画wx.showToast({ title: '刷新完成', icon: 'none' });}, 1500);}
});
五、多媒体
调用摄像头/录音/音频播放等(简要示例)
拍照:
wx.chooseImage({count: 1,sizeType: ['compressed'],sourceType: ['camera'], // 仅拍照success(res) {console.log('拍照成功:', res.tempFilePaths[0]);}
});
播放音频:
const innerAudioContext = wx.createInnerAudioContext();
innerAudioContext.src = 'https://example.com/audio.mp3';
innerAudioContext.play();
innerAudioContext.onPlay(() => {console.log('开始播放');
});
六、文件系统
保存/读取本地文件
保存临时文件到本地:
wx.downloadFile({url: 'https://example.com/test.txt',success(res) {wx.saveFile({tempFilePath: res.tempFilePath,success(saveRes) {console.log('保存成功,路径:', saveRes.savedFilePath);// 可存入缓存供后续使用}});}
});
七、设备传感器调用
获取加速度 wx.onAccelerometerChange()
案例:
Page({onShow() {wx.startAccelerometer({ interval: 'normal' });wx.onAccelerometerChange((res) => {console.log('X:', res.x, 'Y:', res.y, 'Z:', res.z);});},onHide() {wx.stopAccelerometer(); // 页面隐藏时关闭}
});
八、本地数据缓存
wx.setStorageSync()
/ wx.getStorageSync()
案例:
// 保存用户信息
wx.setStorageSync('userInfo', {name: '张三',age: 25
});// 读取
try {const userInfo = wx.getStorageSync('userInfo');if (userInfo) {console.log('用户信息:', userInfo);}
} catch (e) {console.error('读取缓存失败:', e);
}
异步方式:
wx.setStorage({key: 'token',data: 'abc123xyz',success() {console.log('token 已保存');}
});
九、综合性案例:用户登录 + 数据请求 + 缓存 + 跳转
场景:启动时检查登录状态,若无 token 则跳转登录页;若有则请求用户信息并展示。
app.js:
App({onLaunch() {const token = wx.getStorageSync('token');if (!token) {wx.redirectTo({ url: '/pages/login/login' });}}
});
pages/login/login.js:
Page({login() {// 模拟登录请求wx.request({url: 'https://api.example.com/login',method: 'POST',data: { username: 'user', password: '123' },success(res) {if (res.data.token) {wx.setStorageSync('token', res.data.token);wx.setStorageSync('userInfo', res.data.user);wx.switchTab({ url: '/pages/home/home' }); // 跳转 tabBar 页面} else {wx.showToast({ title: '登录失败', icon: 'none' });}}});}
});
pages/home/home.js:
Page({data: { user: null },onLoad() {const user = wx.getStorageSync('userInfo');this.setData({ user });},logout() {wx.removeStorageSync('token');wx.removeStorageSync('userInfo');wx.redirectTo({ url: '/pages/login/login' });}
});
本章小结
微信小程序提供了丰富且易用的 API,涵盖:
- 设备与系统信息:用于适配不同机型
- 网络能力:支持安全 HTTPS 请求、文件上传下载
- 路由跳转:灵活控制页面栈与跨小程序跳转
- UI 交互:弹窗、加载、下拉刷新提升用户体验
- 多媒体与传感器:增强应用交互性
- 本地缓存:实现离线数据存储与用户状态保持
合理组合这些 API,可构建功能完整、体验流畅的小程序应用。
如需进一步扩展(如 WebSocket、地图、支付等),可继续深入官方文档。