前端【小程序】09-小程序基础篇【内置API】【网络请求】【界面交互【Loading、toast】】【本地存储】【API特征】【支持Promise风格的API】【练习】
内置API
内置 API 实际上就是小程序提供的一系列的方法,这些方法都封装在了全局对象 wx
下,调用这些方法实现小程序提供的各种功能,如网络请求、本地存储、拍照、录音等。
① 网络请求
官方文档:https://developers.weixin.qq.com/miniprogram/dev/api/network/request/wx.request.html
调用 wx.request
能够在小程序中发起网络请求与后端接口进行数据的交互,其语法格式如下
1 // 调用API发起网络请求 2 wx.request({ 3 url: '', // 请求接口地址 4 method: '', // 请求方式 5 data: '', // 请求参数, 无论是get还是post请求都这里传参 6 header: {}, // 请求的头信息,注意没有s,不是headers 7 success: () => {}, // 请求成功的回调 8 fail: () => {}, // 请求失败的回调 9 complete: () => {}, // 请求完成的回调 10 })
发起网络请求的示例:
1、前提,请求的接口对应的域名,需要到微信公众号平台->开发->开发管理->开发设置中->服务器域名中添加对应的域名 (如果没有添加的域名直接请求会报错)
2、添加完之后,在开发者工具中,点击右上角详情->项目配置->刷新按钮,把添加的域名刷新出来,会展示到域名信息的request合法域名列表中
3、index.wxml
1 <button class="button" size="mini" type="primary" bind:tap="getBooks">查询书单</button> 2 <view class="books"> 3 <view class="item"> 4 <text>序号</text> 5 <text>名称</text> 6 <text>作者</text> 7 <text>出版社</text> 8 <text>操作</text> 9 </view> 10 <view class="item" wx:for="{{books}}" wx:key="id"> 11 <text>{{index + 1}}</text> 12 <text>{{item.bookname}}</text> 13 <text>{{item.author}}</text> 14 <text>{{item.publisher}}</text> 15 <text>删除</text> 16 </view> 17 </view>
4、index.js
1 Page({ 2 data: { 3 books: [] 4 }, 5 // 调用数据接口的方法 6 getBooks() { 7 // 1、发起请求时,加载提示 8 wx.showLoading({ 9 title: '疯狂加载中', 10 mask: true 11 }) 12 // 2、调用小程序的 API 发起请求 13 wx.request({ 14 url: 'https://hmajax.itheima.net/api/books', 15 method: 'GET', 16 data: { 17 creator: 'zhangsan', 18 }, 19 success: (result) => { // 使用箭头函数,这样内部的this就是指向当前页面实例,如果使用function () {} 这种方式内部的this指向的是success函数本身 20 // 3、请求成功更新数据,渲染页面 21 this.setData({ books: result.data.data }) 22 23 // 4、轻提示 24 wx.showToast({ 25 icon:'success', 26 title: '查询成功' 27 }) 28 }, 29 complete() { 30 wx.hideLoading() // 5、请求完成隐藏加载提示 31 } 32 }) 33 } 34 })
通过设置不校验域名合法性
真机预览/调试
手机端如果出现白屏,需要开启开发模式才能正常预览。
② 界面交互
官方文档:https://developers.weixin.qq.com/miniprogram/dev/api/ui/interaction/wx.showLoading.html
wx.showLoading
显示 loading 提示框title
文字提示内容mask
是否显示透明蒙层,防止触摸穿透
wx.hideLoading
隐藏 loading 提示框wx.showToast
消息提示框(轻提示)mask
是否显示透明蒙层,防止触摸穿透duration
延迟时间(提示框显示多久)icon
指定图标,none
不使用图标
- wx.showLoading 和 wx.showToast 同时只能显示一个
- wx.showLoading 应与 wx.hideLoading 配对使用
1 Page({ 2 data: { 3 books: [] 4 }, 5 // 调用数据接口的方法 6 getBooks() { 7 8 // 加载提示 9 wx:wx.showLoading({ 10 title: '疯狂加载中', 11 mask: true 12 }) 13 // 调用小程序的 API 发起请求 14 wx.request({ 15 url: 'https://hmajax.itheima.net/api/books', 16 method: 'GET', 17 data: { 18 creator: 'zhangsan', 19 }, 20 success: (result) => { 21 // 更新数据,渲染页面 22 this.setData({ books: result.data.data }) 23 24 // 轻提示,消息提示框 25 wx.showToast({ 26 icon:'success', 27 title: '查询成功' 28 }) 29 }, // 防止完成直接把showToast隐藏掉,这里的complete可以改成fail,请求失败的时候才隐藏,这样就只会在失败的时候隐藏showLoading的提示,不会隐藏showToast 30 complete() { 31 wx.hideLoading() // 请求结束后关闭提示, 会隐藏showLoading 并且会隐藏showToast,这会导致查询成功的提示显示的时间很短 32 } 33 }) 34 } 35 })
③ 本地存储
官方文档:https://developers.weixin.qq.com/miniprogram/dev/api/storage/wx.setStorageSync.html
wx.setStorageSync
存入一个数据,复杂类型数据不需要JSON.stringify
处理wx.getStorageSync
读取一个数据,复杂类型数据不需要JSON.parse
处理wx.removeStorageSync
删除一个数据wx.clearStorageSync
清空全部数据
1 Page({ 2 data: { 3 books: [], 4 keyword:'', 5 keywords:[] 6 }, 7 // 调用数据接口的方法 8 getBooks() { 9 10 // 加载提示 11 wx.showLoading({ 12 title: '疯狂加载中', 13 mask: true 14 }) 15 // 调用小程序的 API 发起请求 16 wx.request({ 17 url: 'https://hmajax.itheima.net/api/books', 18 method: 'GET', 19 data: { 20 creator: 'zhangsan', 21 }, 22 success: (result) => { 23 // 更新数据,渲染页面 24 this.setData({ books: result.data.data }) 25 26 // 轻提示 27 wx.showToast({ 28 icon:'success', 29 title: '查询成功' 30 }) 31 }, 32 complete() { 33 wx.hideLoading() 34 } 35 }) 36 }, 37 38 // 本地存储 - 存数据 39 setStorageData() { 40 // 🚨注意:小程序通过 this.data.xxx 获取 data 数据 41 wx.setStorageSync('list', this.data.list) 42 // 轻提示 43 wx.showToast({ icon: 'success', title: '存储成功' }) 44 45 // 同步写法 - 推荐,书写简洁方便 46 // wx.setStorageSync('key', data) 47 // 异步写法 48 // wx.setStorage({ key:'key', data: data, success(){} }) 49 50 // wx.setStorage({ 51 // key: 'list', 52 // data: this.data.list, 53 // success: () => { 54 // wx.showToast({ icon: 'success', title: '存储成功' }) 55 // } 56 // }) 57 }, 58 59 // 本地存储 - 取数据,根据key获取指定的数据 60 getStorageData() { 61 const list = wx.getStorageSync('list') 62 console.log(list); 63 wx.showToast({ icon: 'none', title: '读取成功,看控制台' }) 64 65 // 异步写法 66 // wx.getStorage({ 67 // key: 'list', 68 // success: (res) => { 69 // console.log(res.data) 70 // wx.showToast({ icon: 'none', title: '读取成功,看控制台' }) 71 // } 72 // }) 73 }, 74 75 // 本地存储 - 删数据,根据key删除指定的数据 76 removeStorageData() { 77 wx.removeStorageSync('logs') 78 wx.showToast({ icon: 'success', title: 'logs删除成功' }) 79 }, 80 81 // 本地存储 - 清数据 - 慎用,会将storage中的数据全部清空 82 clearStorageData() { 83 wx.clearStorageSync() 84 wx.showToast({ icon: 'none', title: '清空了全部本地存储' }) 85 } 86 })
④ API 特征
小程序中提供的 API 数量相当的庞大,很难也没有必要将所有的 API 全部掌握,但是这些 API 具有一些共有的特征:
- 异步 API:绝大部分的 API 都是异步方式,通过回调函数获取 API 执行的结果
success
API 调用成功时执行的回调fail
API 调用失败时执行的回调complete
API 调用结束时执行的回调(无论成功或失败)
- 同步 API:部分 API 支持以同步方式获取结果,这些 API 的名称都以
Sync
结尾,如wx.getStorageSync
等 - Promise:部分异步的 API 也支持以 Promise 方式返回结果,此时可以配合
asyc/await
来使用
1 setStorageData() { 3 // 同步写法 - 推荐,书写简洁方便 4 // wx.setStorageSync('key', data) 5 // 异步写法 - 很少用到 6 // wx.setStorage({ key:'key', data: data, success(){} }) 7 8 wx.setStorage({ 9 // 本地存储的key 10 key: 'list', 11 // 本地存储的数据 12 data: this.data.list, 13 // 调用成功的回调 14 success: () => { 15 wx.showToast({ icon: 'success', title: '存储成功' }) 16 } 17 }) 18 }
⑤ 相册/拍照 Promise方式
Promise:部分 API 支持(查看文档)• 配合 async/await
• wx.chooseMedia
官方文档:https://developers.weixin.qq.com/miniprogram/dev/api/media/video/wx.chooseMedia.html
wx.chooseMedia
调起摄像头拍照或读取相册内容,该 API 既支持回调方式获取结果,也支持 Promise 方式返回结果:
1 <view class="preview" bind:tap="onChoose"> 2 <image src="{{ avatar }}" mode="aspectFill" /> 3 </view> 4 ------------------------------------------------- 5 Page({ 6 // 用于页面渲染的数据 7 data: { 8 avatar: '', 9 }, 10 // 选择图片 11 async onChoose() { 12 // 推荐使用 async await 的写法,减少不必要的回调地狱 13 const res = await wx.chooseMedia({ 14 mediaType: ['image'], // 只能拍摄图片或从相册选择图片 15 count: 1, // 指定最多可以选择的文件个数 16 }) 17 this.setData({ // 等待选择完,将选择的内容赋值给avatar变量,展示到页面视图 18 avatar: res.tempFiles[0].tempFilePath, 19 }) 20 }, 21 })
搜索小练习
index.wxml
1 <!-- 搜索历史 --> 2 <view class="history"> 3 <view class="search-bar"> 4 <input type="text" model:value="{{ keyword }}" /> 5 <text class="label" bind:tap="onSearch">搜索</text> 6 </view> 7 <view class="title" wx:if="{{ keywords.length }}"> 8 历史搜索 <text class="icon-delete" bind:tap="onClear">x</text> 9 </view> 10 <view class="keywords"> 11 <!-- wx:key="*this" *this 表示当前这条数据本身 --> 12 <navigator url="/pages/test/index" wx:for="{{ keywords }}" wx:key="*this"> 13 {{ item }} 14 </navigator> 15 </view> 16 </view>
index.js
1 Page({ 2 data: { 3 keyword: '', 4 keywords: [] 5 }, 6 7 onSearch () { 8 const keyword = this.data.keyword.trim() 9 10 // 非空判断 11 if (keyword === '') { 12 return wx.showToast({ 13 icon: 'none', 14 title: '请输入搜索内容' 15 }) 16 } 17 18 const arr = [keyword, ...this.data.keywords] 19 this.setData({ 20 keywords: Array.from(new Set(arr)), 21 keyword: '' 22 }) 23 } 24 })
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具