Taro自带方法(小程序必用)

1.跳转到 tabBar 页面,并关闭其他所有非 tabBar 页面

 Taro.switchTab({ url: '/pages/index/index' });

2.隐藏 tabBar

Taro.hideTabBar();

3.保留当前页面,跳转到应用内的某个页面。但是不能跳到 tabbar 页面。使用 Taro.navigateBack 可以返回到原页面。小程序中页面栈最多十层。

Taro.navigateTo({url: ''});

4.返回上一页/上几页

Taro.navigateBack({
  delta: 1
})

5…关闭当前页面,跳转到应用内的某个页面。但是不允许跳转到 tabbar 页面。

Taro.redirectTo({url: ''});       

6.显示/隐藏当前页面的转发按钮

Taro.showShareMenu({});
Taro.hideShareMenu();

7.更新转发属性

Taro.updateShareMenu({
  withShareTicket: true,
  success () { }
})

8.获取转发详细信息

Taro.getShareInfo();

9.显示 loading 提示框。需主动调用 Taro.hideLoading 才能关闭提示框

Taro.showLoading({ title: '加载中', mask: true });
Taro.hideLoading();

10.显示消息提示框(默认三秒后自动关闭)

Taro.showToast({ title: '提交订单未成功', icon: 'none' });
Taro.hideToast();

11.显示操作菜单

Taro.showActionSheet({
  itemList: ['A', 'B', 'C'],
  success: function (res) {
    console.log(res.tapIndex)
  },
  fail: function (res) {
    console.log(res.errMsg)
  }
})

12.显示模态对话框

Taro.showModal({
    title: '提示',
    showCancel: false,
    confirmText: '我知道了',
    content: '你成功了',
    success: () => {
        
    }
});

13.开始/停止当前页面下拉刷新。

Taro.startPullDownRefresh();
Taro.stopPullDownRefresh();

14.动态设置当前页面的标题

Taro.setNavigationBarTitle({ title: res.data.name });
Taro.setNavigationBarColor({
    frontColor: '#ffffff',
    backgroundColor: '#ff0000',
    animation: {
        duration: 400,
        timingFunc: 'easeIn'
    }
})

15.隐藏返回上页按钮

Taro.hideHomeButton();

16.发起微信支付
https://developers.weixin.qq.com/miniprogram/dev/api/open-api/payment/wx.requestPayment.html

Taro.requestPayment({
  timeStamp: '',
  nonceStr: '',
  package: '',
  signType: 'MD5',
  paySign: '',
  success: function (res) { },
  fail: function (res) { }
})

17.支付各个安全场景验证人脸

Taro.faceVerifyForPay(params).then(...);

18.请求订阅消息

Taro.requestSubscribeMessage({
   tmplIds
});

19.监听事件 on once off tigger

Taro.eventCenter.on(UserEvents.LOGIN, this.getMemberInfo);
Taro.eventCenter.off(SubsiteEvents.SUBSITE_CHANGED, this.getCategory);
Taro.eventCenter.trigger('categoryNavigate.selected', id !== 0, id);

20.调起客户端扫码界面,扫码成功后返回对应的结果

 Taro.scanCode({})

21.在新页面中全屏预览图片。预览的过程中用户可以进行保存图片、发送给朋友等操作。

 Taro.previewImage({
      current: pageData.image.imgUrl,
      urls: [pageData.image.imgUrl]
  });

22.保存图片到系统相册。需要用户授权 scope.writePhotosAlbum

Taro.saveImageToPhotosAlbum({
  success: function (res) { }
})

23.获取图片信息

Taro.getImageInfo({
  src: 'images/a.jpg',
  success: function (res) {
    console.log(res.width)
    console.log(res.height)
  }
})

24.从本地相册选择图片或使用相机拍照。

Taro.chooseImage({
  count: 1, // 默认9
  sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
  sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有,在H5浏览器端支持使用 `user``environment`分别指定为前后摄像头
  success: function (res) {
    // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
    var tempFilePaths = res.tempFilePaths
  }
})

25.压缩图片接口,可选压缩质量

Taro.compressImage({
  src: '', // 图片路径
  quality: 80 // 压缩质量
})

26.从客户端会话选择文件。

Taro.chooseMessageFile({
  count: 10,
  type: 'image',
  success: function (res) {
    // tempFilePath可以作为img标签的src属性显示图片
    const tempFilePaths = res.tempFilePaths
  }
})

27.拍摄或从手机相册中选择图片或视频。

Taro.chooseMedia({
  count: 9,
  mediaType: ['image','video'],
  sourceType: ['album', 'camera'],
  maxDuration: 30,
  camera: 'back',
  success: (res) => {
    console.log(res.tempFiles)
    console.log(res.type)
  }
})

28.保存文件到本地。注意:saveFile 会把临时文件移动,因此调用成功后传入的 tempFilePath 将不可用

Taro.chooseImage({
  success: function (res) {
    var tempFilePaths = res.tempFilePaths
    Taro.saveFile({
      tempFilePath: tempFilePaths[0],
      success: function (res) {
        var savedFilePath = res.savedFilePath
      }
    })

}
})

29.删除该小程序下已保存的本地缓存文件

Taro.getSavedFileList({
  success: function (res) {
    if (res.fileList.length > 0){
      Taro.removeSavedFile({
        filePath: res.fileList[0].filePath,
        complete: function (res) {
          console.log(res)
        }
      })
    }

}
})

30.新开页面打开文档,支持格式

Taro.downloadFile({
  url: 'http://example.com/somefile.pdf',
  success: function (res) {
    var filePath = res.tempFilePath
    Taro.openDocument({
      filePath: filePath,
      success: function (res) {
        console.log('打开文档成功')
      }
    })
  }
})

31.获取本地已保存的文件列表

Taro.getSavedFileList({
  success: function (res) {
    console.log(res.fileList)
  }
})

32.获取本地文件的文件信息。此接口只能用于获取已保存到本地的文件,若需要获取临时文件信息,请使用 Taro.getFileInfo 接口。

Taro.getSavedFileInfo({
  filePath: 'wxfile://somefile', //仅做示例用,非真正的文件路径
  success: function (res) {
    console.log(res.size)
    console.log(res.createTime)
  }
})

33.获取该小程序下的 本地临时文件 或 本地缓存文件 信息

Taro.getFileInfo({
    success: function (res) {
        console.log(res.size)
        console.log(res.digest)
    }
})

34.获取全局唯一的文件管理器

  Taro.getFileSystemManager()

35.创建 canvas 的绘图上下文 CanvasContext 对象

/*创建离屏 canvas 实例*/
Taro.createOffscreenCanvas()
/*创建 canvas 的绘图上下文 CanvasContext  对象*/
Taro.createCanvasContext('canvas')
/*把当前画布指定区域的内容导出生成指定大小的图片。在 draw() 回调里调用该方法才能保证图片导出成功。*/
Taro.canvasToTempFilePath({
  x: 100,
  y: 200,
  width: 50,
  height: 50,
  destWidth: 100,
  destHeight: 100,
  canvasId: 'myCanvas',
  success: function (res) {
    console.log(res.tempFilePath)
  }
})
/*将像素数据绘制到画布。在自定义组件下,第二个参数传入自定义组件实例 this,以操作组件内 <canvas> 组件*/
const data = new Uint8ClampedArray([255, 0, 0, 1])
Taro.canvasPutImageData({
  canvasId: 'myCanvas',
  x: 0,
  y: 0,
  width: 1,
  data: data,
  success: function (res) {}
})
/*获取 canvas 区域隐含的像素数据。*/
Taro.canvasGetImageData({
  canvasId: 'myCanvas',
  x: 0,
  y: 0,
  width: 100,
  height: 100,
  success: function (res) {
    console.log(res.width) // 100
    console.log(res.height) // 100
    console.log(res.data instanceof Uint8ClampedArray) // true
    console.log(res.data.length) // 100 * 100 * 4
  }
})

36.将页面滚动到目标位置,支持选择器和滚动距离两种方式定位

Taro.pageScrollTo({
    scrollTop: 0,
    duration: 300
});

37.此接口可获取支付宝会员的基础信息(头像图片地址、昵称、性别、国家码、省份、所在市区),接入方法请参考 获取会员基础信息介绍。如需获取支付宝会员标识(user_id),请调用 my.getAuthCode 和 alipay.system.oauth.token 接口。

Taro.getOpenUserInfo();

38.获取全局唯一的版本更新管理器,用于管理小程序更新。 关于小程序的更新机制,可以查看运行机制 文档。(https://developers.weixin.qq.com/miniprogram/dev/framework/runtime/operating-mechanism.html)

const updateManager = Taro.getUpdateManager()
  updateManager.onCheckForUpdate(function (res) {
  // 请求完新版本信息的回调
  console.log(res.hasUpdate)
})
updateManager.onUpdateReady(function () {
  Taro.showModal({
    title: '更新提示',
    content: '新版本已经准备好,是否重启应用?',
    success: function (res) {
      if (res.confirm) {
        // 新的版本已经下载好,调用 applyUpdate 应用新版本并重启
        updateManager.applyUpdate()
      }
    }
  })
})
updateManager.onUpdateFailed(function () {
  // 新的版本下载失败
})

39.将 Base64 字符串转成 ArrayBuffer 数据。

const base64 = 'CxYh'
const arrayBuffer = Taro.base64ToArrayBuffer(base64)

40.将 ArrayBuffer 数据转成 Base64 字符串。

const arrayBuffer = new Uint8Array([11, 22, 33])
const base64 = Taro.arrayBufferToBase64(arrayBuffer)

41.云函数

//在调用云开发各 API 前,需先调用初始化方法 init 一次(全局只需一次,多次调用时只有第一次生效)

Taro.cloud.init({
  env: 'test-x1dzi'
})

//调用云函数
 假设已有一个云函数 add,在小程序端发起对云函数 add 的调用:  
Taro.cloud.callFunction({
// 要调用的云函数名称
name: 'add',
  // 传递给云函数的event参数
  data: {
    x: 1,
    y: 2,
  }
}).then(res => {
  // output: res.result === 3
}).catch(err => {
  // handle error
})

//将本地资源上传至云存储空间,如果上传至同一路径则是覆盖写

Taro.cloud.uploadFile({
  cloudPath: 'example.png',
  filePath: '', // 文件路径
  success: res => {
    // get resource ID
    console.log(res.fileID)
  },
  fail: err => {
    // handle error
  }
})

//从云存储空间下载文件

Taro.cloud.downloadFile({
  fileID: 'a7xzcb',
  success: res => {
    // get temp file path
    console.log(res.tempFilePath)
  },
  fail: err => {
    // handle error
  }
})

//用云文件 ID 换取真实链接,公有读的文件获取的链接不会过期,私有的文件获取的链接十分钟有效期。一次最多取 50 个。

Taro.cloud.getTempFileURL({
  fileList: [{
    fileID: 'a7xzcb',
    maxAge: 60 * 60, // one hour
  }]
}).then(res => {
  // get temp file URL
  console.log(res.fileList)
}).catch(error => {
  // handle error
})
Taro.cloud.getTempFileURL({ fileList: ['cloud://xxx', 'cloud://yyy'], success: res => {
// get temp file URL
console.log(res.fileList)
}, fail: err => {
// handle error
} })


//从云存储空间删除文件,一次最多 50 个

.cloud.deleteFile({
  fileList: ['a7xzcb']
}).then(res => {
  // handle success
  console.log(res.fileList)
}).catch(error => {
  // handle error
})
Taro.cloud.deleteFile({ fileList: ['a7xzcb'], success: res => {
// handle success
console.log(res.fileList)
}, fail: err => {
// handle error
}, complete: res => {
// ...
} })


获取数据库实例
 以下调用获取默认环境的数据库的引用:  
const db = Taro.cloud.database()
const testDB = Taro.cloud.database({
  env: 'test-123'
})
  • 10
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值