微信小程序:结合回调函数操作API
来自CloudWiki
怎样读懂官方文档,
怎样在官方文档基础上去做开发。
例1:wx.getImageInfo(Object object)
我们先来看媒体中的获取图片信息的函数:
wx.getImageInfo(Object object)
该函数的作用是获取图片信息。网络图片需先配置download域名才能生效。
函数参数:
object.success 回调函数参数:
res.orientation 的合法值:
代码示例
//index.js
const app=getApp() Page({ data:{ src:'../../imgs/pic.jpg' }, getImgInfo:function(){ wx.getImageInfo({ src:this.data.src, success(res) { //回调函数 console.log(res) }, fail(res){ console.log(res) }, complete(res){ console.log('一定会执行') } }) } })
index.wxml
<view>下面是一个获取图片信息的按钮</view> <button bindtap='getImgInfo'>点一下</button>
运行
输出图片信息:
{errMsg: "getImageInfo:ok", width: 1280, height: 1810, type: "jpeg", orientation: "up", …}errMsg: "getImageInfo:ok"height: 1810orientation: "up"path: "img/guonian2.jpg"type: "jpeg"width: 1280__proto__: Object index.js? [sm]:16 一定会执行
例2:wx.showToast
再来看一下界面交互中的wx.showToast函数
该函数的作用是显示消息提示框
函数参数:
代码示例
index.js
const app=getApp() Page({ data:{ src:'/img/guonian2.jpg' }, //事件触发函数 showImgInfo:function(text){ wx.showToast({ title: text, icon:'none' //消除对号 }) }, getImgInfo:function(){ var that=this//及时保存当前的变量,为回调函数做准备 wx.getImageInfo({ src: this.data.src, success(res) { // 回调函数 委托 执行者变化 that.showImgInfo('路径->'+res.path+'\n尺寸'+res.width+'X'+res.height) }, fail(res){ console.log(res) }, complete(res){ console.log('一定会执行',res) } }) } })
运行,获得图片信息,并在交互界面看到所输出的图片信息