uniapp 微信小程序扫描 uni.scanCode

一、使用环境

  • 编译环境:HBuilder X
  • 运行环境 :微信开发者工具

二、二维码生成

使用的是草料二维码:草料网址二维码生成器

选择网址---输入网址和参数---生成二维码

uniapp 微信小程序扫描 uni.scanCode_第1张图片

三、业务实现

业务需求:点击扫码按钮调起扫码功能,扫码成功后返回对应的结果并跳转页面

说明:在微信开发者工具中,无法扫码。需要真机验证(或者在电脑上存放生成的二维码照片,点击扫描查看打印结果)

调用方法:uni.scanCode

官方文档:uni.scanCode(OBJECT) | uni-app官网

完整代码地址:front-mini-programe/components/tabbar/tabbar.vue · cheinlu/土拨鼠充电系统 - Gitee.com

代码示例:

//点击tabbar按钮
const handleTabbarItemClick = (item, index) => {
  if (active.value !== index) {
    //如果点击的是扫描按钮
    if (index === 1) {
      uni.scanCode({
        success(res) {
          console.log('res',res);
          const scanUrl = res.result  //保存扫描结果
          const regExp = /pileId=(\d+)&code=(\d+)/ //用于匹配URL中的pileId和code参数
          const matchResult = scanUrl.match(regExp) 
          let pileId = ''
          let code = ''
          //判断是否成功匹配到pileId和code。
          if (matchResult) {
            pileId = matchResult[1]
            code = matchResult[2]
          }
          //匹配成功就跳转到charging页面
          uni.reLaunch({
            url: '/subpkg/charging/charging?pileId=' + pileId + '&code=' + code
          })
        }
      })
    } else {
      active.value = index // 更新选中项的索引
      const path = item.pagePath
      uni.switchTab({
        url: path
      })
    }
  }
}

res打印的结果

其中,result就是扫码的内容,也就是前面生成的二维码地址

uniapp 微信小程序扫描 uni.scanCode_第2张图片

你可能感兴趣的:(uni-app,微信小程序,小程序)