uniapp 扫码二维码实现 微信小程序 || APP || H5

功能

微信小程序 || APP || H5 平台使用相机或者从相册扫码二维码

图示

在这里插入图片描述
H5

注意H5 使用zxing实现需引入ZXing

npm add @zxing/library

代码实现

index.vue

<template>
  <!-- 保持原有模板结构不变 -->
  <view class="container">
    <!-- 导航栏 -->
    <!-- <uni-nav-bar title="扫码识别" backgroundColor="#2F7AF6" color="#fff" :border="false"></uni-nav-bar> -->

    <!-- 操作按钮 -->
    <!-- #ifdef MP-WEIXIN || APP || H5 -->
    <view class="action-bar">
      <button class="scan-button" @click="startScan" :loading="isScanning">开始扫码</button>
    </view>
    <!-- #endif -->

    <!-- 提示区域 -->
    <view class="scan-area">
      <!-- 微信小程序 || APP || H5 -->
      <!-- #ifdef (MP-WEIXIN || APP || H5)  -->
      <view class="platform-tip">
        <text>点击上方按钮开始扫码</text>
      </view>
      <!-- #endif -->

      <!-- 不支持平台 -->
      <!-- #ifndef (MP-WEIXIN || APP || H5) -->
      <view class="unsupport-tip">
        <text>当前平台暂不支持扫码功能</text>
      </view>
      <!-- #endif -->
    </view>

    <!-- 扫描结果 -->
    <view class="result-box">
      <view class="result-header">
        <text>扫描结果</text>
        <text class="copy-btn" @click="copyResult">复制</text>
      </view>
      <scroll-view scroll-y class="result-content">
        <text class="result-text">{{ scanResult }}</text>
      </scroll-view>
    </view>
  </view>
</template>

<script>
const ERROR_MAPPING = {
  'cancel': { isCancel: true, message: '扫码已取消' },
  'auth denied': { message: '未授权相机权限,请开启权限后重试' }
}

export default {
  data() {
    return {
      isScanning: false,
      scanResult: '',
    }
  },
  onShow() {
    uni.$on('scanH5Complete', this.handleScanResult)
  },
  onUnload() {
    uni.$off('scanH5Complete', this.handleScanResult)
  },
  methods: {
    async startScan() {
      this.isScanning = true
      try {
        this.scanResult = (await this.performScan()).result
      } catch (e) {
        const msg = e?.message || '未知错误'
        this.scanResult = `扫码失败:${msg}`
      } finally {
        this.isScanning = false
      }
    },
    async performScan() {
      // #ifdef H5
      return this.performH5Scan()
      // #endif
      // #ifndef H5
      return new Promise((resolve, reject) => {
        uni.scanCode({
          success: (res) => {
            if (!res?.result) return reject(new Error('扫码内容为空'))
            resolve(res)
          },
          fail: (err) => {
            const errMsg = err?.errMsg?.toString() || ''
            const matchedKey = Object.keys(ERROR_MAPPING).find(key => errMsg.includes(key))
            reject(new Error(matchedKey ? ERROR_MAPPING[matchedKey].message : '扫码失败'))
          }
        })
      })
      // #endif
    },
    performH5Scan() {
      uni.navigateTo({
        url: '/pages/scan/scanH5'
      })
    },
    handleScanResult(result) {
      this.scanResult = result
      uni.showToast({
        title: '扫码成功',
        icon: 'success',
        duration: 1500
      })
    },
    copyResult() {
      if (!this.scanResult) {
        uni.showToast({ title: '无内容可复制', icon: 'none' })
        return
      }

      // #ifdef H5
      navigator.clipboard.writeText(this.scanResult).then(() => {
        uni.showToast({ title: '复制成功', icon: 'success' })
      }).catch(() => {
        uni.showToast({ title: '复制失败', icon: 'none' })
      })
      // #endif

      // #ifndef H5
      uni.setClipboardData({
        data: this.scanResult,
        success: () => uni.showToast({ title: '已复制到剪贴板' }),
        fail: () => uni.showToast({ title: '复制失败', icon: 'none' })
      })
      // #endif
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden; // 禁止溢出滚动
  box-sizing: border-box; // 包含内边距
  background-color: #f5f5f5;
}

.scan-area {
  flex-shrink: 0;
  /* 防止压缩 */
  padding: 0px;
  text-align: center;
  font-size: 16px;
  color: #333;
}

.platform-tip,
.unsupport-tip {
  color: #666;
  font-size: 16px;
  line-height: 1.5;
}

.h5-scan-area {
  position: relative;
  margin: 0px auto;
  border: 0px solid #2F7AF6;
  overflow: hidden;
}

.video-preview {
  width: 100%;
  height: 300px;
  transition: opacity 0.3s;
}

.h5-tip {
  // 提升层级
  z-index: 999;
  // 调整定位方式
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%); // 改为完全居中
  bottom: auto;
  width: 80%;
  // 添加边界保护
  pointer-events: none; // 防止点击穿透
  white-space: nowrap; // 单行显示
}

.action-bar {
  padding: 16px;
  display: flex;
  justify-content: center;
}

.scan-button {
  width: 100%;
  height: 45px;
  background-color: #2F7AF6;
  color: #fff;
  border-radius: 40px;
}

.result-box {
  /* 关键属性-占据剩余空间 */
  flex: 1;
  overflow: hidden; // 禁止外部滚动
  margin: 16px 16px 0 16px;
  border: 1px solid #eee;
  border-radius: 12px;
  background: #fff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.result-header {
  padding: 16px;
  font-weight: 600;
  color: #2F7AF6;
  border-bottom: 1px solid #f0f0f0;
}

.result-content {
  /* 继承父级剩余高度 */
  flex: 1;
  /* 保证最小可读区域 */
  min-height: 100px;
  height: calc(100vh - 260px); // 根据实际header高度调整
  padding: 16px;
  background: #fafafa;
}

.result-text {
  white-space: pre-wrap;
  word-break: break-word;
  font-family: Monaco, Consolas, monospace;
  line-height: 1.8;
  color: #333;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;

  .copy-btn {
    color: #2F7AF6;
    font-size: 14px;
    padding: 4px 12px;
    border: 1px solid #2F7AF6;
    border-radius: 16px;
    transition: all 0.2s;

    &:active {
      background: rgba(47, 122, 246, 0.1);
    }

    &[disabled] {
      opacity: 0.5;
      pointer-events: none;
    }
  }
}
</style>

scanH5.vue

<template>
  <view class="scan-container">
    <view class="scan-area">
      <video id="video_nav_id" class="video-preview" :controls="false" object-fit="fill"></video>
      <view class="scan-frame">
        <view class="scan-line"></view>
      </view>
      <view class="scan-tip">将目标码放入框内,即可自动扫描</view>
    </view>

    <!-- 操作栏容器 -->
    <view class="action-bar">
      <view class="album-icon" @click="chooseImage">
        <image src="/static/images/icon/album-icon.png" mode="aspectFit" class="icon-img" />
        <text class="album-text">相册</text>
      </view>
      <button class="dingtalk-btn cancel-btn" @click="stopScan" hover-class="dingtalk-btn-hover">
        取消
      </button>
    </view>
  </view>
</template>

<script>
import { BrowserMultiFormatReader } from '@zxing/library'

export default {
  data() {
    return {
      codeReader: null,
      videoElement: null
    }
  },
  onLoad() {
    this.$nextTick(() => {
      const videoContainer = document.getElementById('video_nav_id')
      if (videoContainer) {
        this.videoElement = videoContainer.getElementsByTagName('video')[0]
        console.log('视频元素状态:', this.videoElement ? '存在' : '不存在')
        this.videoElement?.setAttribute('id', 'video_id')
      }
    })
    this.codeReader = new BrowserMultiFormatReader()
    this.startScan()
  },
  onUnload() {
    if (this.codeReader) {
      this.codeReader.reset()
      this.codeReader = null
    }
  },
  methods: {
    async chooseImage() {
      try {
        uni.chooseImage({
          count: 1,
          sizeType: ['original'], //可以指定是'original', 'compressed',默认二者都有
          sourceType: ['album'], //从相册选择
          success: async (res) => {
            if (res.tempFilePaths.length > 0) {
              const image = new Image()
              image.src = res.tempFilePaths[0]
              image.onload = async () => {
                try {
                  const result = await this.codeReader.decodeFromImage(image)
                  this.handleSuccess(result.text)
                } catch (error) {
                  this.handleError({
                    message: '图片解码失败',
                    type: 'IMAGE_DECODE_FAILED'
                  })
                }
              }
            }
          }
        });
      } catch (error) {
        this.handleError(error)
      }
    },
    async startScan() {
      try {
        const devices = await this.codeReader.getVideoInputDevices()
        if (devices.length === 0) {
          uni.showToast({ title: '未检测到可用摄像头', icon: 'none' })
          return
        }
        await this.codeReader.decodeFromVideoDevice(
          null,
          this.videoElement,
          (result, error) => {
            if (result) this.handleSuccess(result.text)
          }
        )
      } catch (error) {
        this.handleError(error)
      }
    },
    handleSuccess(result) {
      uni.$emit('scanH5Complete', result)
      uni.navigateBack()
    },
    handleError(error) {
      let msg = error.message || '扫码失败'
      uni.$emit('scanH5Complete', msg)
      uni.showToast({
        title: msg,
        icon: 'none'
      })
      setTimeout(() => uni.navigateBack(), 1500)
    },
    stopScan() {
      uni.$emit('scanH5Complete', '扫码已取消')
      uni.navigateBack()
    }
  }
}
</script>

<style scoped>
.scan-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-color: #000;
}

.video-preview {
  width: 100%;
  height: 100%;
  opacity: 0.7;
}

.scan-area {
  position: relative;
  height: 100vh;
  overflow: hidden;
}

.scan-frame {
  position: absolute;
  top: 40%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 70vw;
  height: 70vw;
  max-width: 500px;
  max-height: 500px;
  border: 2px solid #1677FF;
  border-radius: 8px;
  box-shadow: 0 0 20px rgba(22, 119, 255, 0.3);
}

.scan-line {
  height: 2px;
  background: #1677FF;
  animation: scan 2s infinite linear;
}

@keyframes scan {
  0% {
    transform: translateY(0)
  }

  100% {
    transform: translateY(250px)
  }
}

.scan-tip {
  position: absolute;
  top: 80px;
  width: 100%;
  text-align: center;
  color: #fff;
  font-size: 14px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
}

.action-bar {
  position: fixed;
  bottom: 40px;
  left: 0;
  width: 100%;
  transform: none;
  display: flex;
  align-items: center;
  gap: 40px;
  justify-content: center;
}

.album-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #82848a;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.album-icon {
  /* 修改为垂直排列 */
  flex-direction: column;
  gap: 6px;
  height: 60px;
  width: 60px;
}

.album-text {
  color: #fff;
  font-size: 12px;
  line-height: 1;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

.icon-img {
  width: 28px;
  height: 28px;
}

.cancel-btn {
  width: 200px;
  background: #f9d39b;
  color: #333;
  border: 1px solid #eee;
  margin: 0;
  /* 移除原有定位 */
}
</style>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值