Vue3使用vue-qrcode-reader实现扫码绑定设备功能(推荐)

 更新时间:2024年10月21日 10:02:55   作者:鱼是一只鱼啊  
本文介绍了在Vue3中使用vue-qrcode-reader版本5.5.7来实现移动端的扫码绑定设备功能,用户通过扫描二维码自动获取设备序列号,并填充到添加设备界面,完成设备绑定的全过程,包含ScanCode.vue和DeviceAdd.vue两个主要界面的实现方式

需求描述

移动端进入网站后,登录网站进入设备管理界面。点击添加设备,可以选择直接添加或者扫一扫。点击扫一扫进行扫描二维码获取设备序列号自动填充到添加设备界面的序列号输入框中。然后点击完成进行设备绑定。

安装vue-qrcode-reader 这里使用的版本是5.5.7

npm install vue-qrcode-reader --save

扫一扫界面ScanCode.vue

<template>
  <div class="block-main">
    <div class="head-wrap">
      <img
        src="../../assets/images/mobile/icon-arrow-left.png"
        class="btn-back"
        @click="goback"
      />
      <span class="title">扫一扫</span>
    </div>
    <div class="qr-container">
      <qrcode-stream
        @detect="onDecode"
        @camera-on="onCameraReady"
        @error="onError"
      />
    </div>
  </div>
</template>
<script>
import { reactive, ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { QrcodeStream } from "vue-qrcode-reader";
import { showToast } from "vant";
export default {
  components: {
    QrcodeStream,
    showToast,
  },
  setup() {
    const testVice = reactive([]);
    const router = useRouter();
    // 扫码成功后的回调
    const onDecode = (detectedCodes) => {
      if (detectedCodes.length > 0) {
        // 跳转到添加设备页面并传递设备编号
        let deviceCode = detectedCodes[0].rawValue;
        router.replace({
          path: "/deviceadd",
          query: { deviceCode },
        });
      } else {
        showToast("扫码失败");
      }
    };
    const onCameraReady = (res) => {
      console.log("摄像头准备好了");
    };
    const onError = (error) => {
      if (error.name === "NotAllowedError") {
        // user denied camera access permission
        showToast("用户拒绝相机访问权限");
      } else if (error.name === "NotFoundError") {
        // no suitable camera device installed
        showToast("未安装合适的摄像设备");
      } else if (error.name === "NotSupportedError") {
        // page is not served over HTTPS (or localhost)
         showToast("当前网页没有通过 HTTPS 或 localhost 安全协议提供服务");
      } else if (error.name === "NotReadableError") {
        // maybe camera is already in use
        showToast("相机被占用了)");
      } else if (error.name === "OverconstrainedError") {
        // did you request the front camera although there is none?
         showToast("尝试使用前置摄像头)");
      } else if (error.name === "StreamApiNotSupportedError") {
        showToast("浏览器似乎缺少功能)");
        // browser seems to be lacking features
      }
    };
    onMounted(() => {
      navigator.mediaDevices
        .enumerateDevices()
        .then((devices) => {
          devices.forEach((device) => {
            if (device.kind === "videoinput") {
              console.log(
                "Video input device: ",
                device.label,
                device.deviceId
              );
            }
          });
        })
        .catch((error) => {
          console.error("Error enumerating devices: ", error);
          showToast("Error enumerating devices");
        });
    });
    const goback = () => {
      router.go(-1);
    };
    return {
      testVice,
      onCameraReady,
      goback,
      onDecode,
      onError,
    };
  },
};
</script>
<style lang="scss" scoped>
.block-main {
  height: 100%;
  background: #fff;
  overflow: hidden;
  font-size: 16px;
  .head-wrap {
    height: 0.96rem;
    background: #31be7c;
    font-family: Microsoft YaHei UI;
    font-weight: 400;
    color: #fff;
    display: flex;
    align-items: center;
    position: fixed;
    left: 0;
    right: 0;
    .btn-back {
      margin-left: 0.4rem;
      width: 0.22rem;
      height: 0.38rem;
    }
    .title {
      font-size: 0.36rem;
      text-align: center;
      flex: 1;
    }
  }
  .qr-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: calc(100vh - 0.96rem); // 减去头部的高度
    margin-top: 0.96rem;
  }
}
</style>

添加设备界面DeviceAdd.vue

<template>
  <div class="block-main">
    <div class="head-wrap">
      <a href="javascript:void(0)" rel="external nofollow"  rel="external nofollow"  class="btn-cancel" @click="goBack">取消</a>
      <span class="title"></span>
      <a href="javascript:void(0)" rel="external nofollow"  rel="external nofollow"  class="btn-sure" @click="deviceReg">完成</a>
    </div>
    <div class="input-wrap" @click="showDeviceType">
      <span class="input">{{ deviceInfo.devtypeName }}</span>
      <img
        src="../../assets/images/mobile/icon-arrow-right.png"
        class="icon-arrow"
      />
    </div>
    <div class="input-wrap">
      <input
        type="text"
        class="input"
        v-model="deviceInfo.devsn"
        placeholder="请输入设备序列号"
      />
      <img
        v-if="deviceInfo.devsn"
        src="../../assets/images/mobile/icon-close-gray.png"
        class="icon-close"
        @click="clearInput"
      />
    </div>
    <div class="error-msg">{{ deviceInfo.devsn_error }}</div>
    <van-popup v-model:show="deviceTypeDialog" position="bottom">
      <van-picker
        :columns="devTypes"
        v-model:value="deviceInfo.devtype"
        @cancel="deviceTypeDialog = false"
        @confirm="onConfirm"
      />
    </van-popup>
  </div>
</template>
<script>
import { ref, reactive, onMounted } from "vue";
import { useRoute,useRouter } from "vue-router";
import {
  Picker,
  Popup,
  showFailToast,
  showSuccessToast,
  showToast,
  showLoadingToast,
} from "vant";
import { device_Reg } from "../../api/auth";
export default {
  components: {
    "van-picker": Picker,
    "van-popup": Popup,
  },
  setup() {
    const route = useRoute();
    const deviceTypeDialog = ref(false);
    const router = useRouter();
    const devTypes = [
      { value: 1, text: "设备类型1" },
      { value: 2, text: "设备类型2" },
      { value: 3, text: "设备类型3" },
    ];
    const deviceInfo = reactive({
      devtype: null,
      devtypeName: "请选择需要绑定的设备",
      devsn: "",
      devsn_error: "",
    });
    const showDeviceType = () => {
      deviceTypeDialog.value = true;
    };
    const clearInput = () => {
      deviceInfo.devsn = "";
      deviceInfo.devsn_error = "";
    };
    const onConfirm = ({ selectedOptions }) => {
      deviceTypeDialog.value = false;
      deviceInfo.devtype = selectedOptions[0].value;
      deviceInfo.devtypeName = selectedOptions[0].text;
    };
    const goBack = () => {
      router.go(-1);
    };
    const deviceReg = async () => {
      if (deviceInfo.devtype == null) {
        deviceInfo.devsn_error = "请选择设备类型";
        return;
      }
      if (!deviceInfo.devsn) {
        deviceInfo.devsn_error = "请填写设备序列号";
        return;
      }
      const toast = showLoadingToast({
        message: "数据提交中...",
        forbidClick: true,
      });
      let response = await device_Reg({
        devsn: deviceInfo.devsn,
        devtype: deviceInfo.devtype,
      });
      if (response.isSuccess == true) {
        toast.close();
        showSuccessToast("设备绑定成功");
        setTimeout(() => {
          router.go(-1);
        }, 2000);
      } else {
        deviceInfo.devsn_error = response.message;
        toast.close();
      }
    };
    onMounted(() => {
      const scannedDeviceSn = route.query.deviceCode;
      if (scannedDeviceSn) {
        deviceInfo.devsn = scannedDeviceSn;
      }
    });
    return {
      devTypes,
      deviceTypeDialog,
      deviceInfo,
      showDeviceType,
      clearInput,
      onConfirm,
      goBack,
      deviceReg,
    };
  },
};
</script>
<style lang="scss" scoped>
.block-main {
  height: auto;
  overflow: hidden;
  .head-wrap {
    height: 0.96rem;
    background: #31be7c;
    font-family: Microsoft YaHei UI;
    font-weight: 400;
    color: #fff;
    display: flex;
    align-items: center;
    .btn-cancel {
      padding-left: 0.4rem;
      padding-right: 0.4rem;
      height: 0.96rem;
      line-height: 0.96rem;
      font-size: 0.36rem;
      color: #fff;
    }
    .title {
      font-size: 0.36rem;
      text-align: center;
      flex: 1;
    }
    .btn-sure {
      width: 1.15rem;
      height: 0.55rem;
      background: #ffffff;
      border-radius: 5px;
      font-size: 0.36rem;
      line-height: 0.55rem;
      margin-right: 0.4rem;
      margin-left: 0.4rem;
      color: #31be7c;
    }
  }
  .input-wrap {
    height: 1.2rem;
    line-height: 1.2rem;
    border-bottom: 1px solid #ced6d2;
    display: flex;
    align-items: center;
    .input {
      flex: 1;
      margin-left: 0.58rem;
      font-size: 0.3rem;
      width: 0px;
      border-style: none;
      outline: none;
      height: 1rem;
      text-align: left;
    }
    .icon-close {
      width: 0.36rem;
      height: 0.36rem;
      margin-right: 0.4rem;
      margin-left: 0.4rem;
    }
    .icon-arrow {
      width: 0.2rem;
      height: 0.3rem;
      margin-left: 0.04rem;
      margin-right: 0.4rem;
      margin-left: 0.4rem;
    }
  }
  .error-msg {
    padding-left: 0.58rem;
    margin-top: 0.19rem;
    font-size: 0.24rem;
    color: #ff6c00;
    padding-right: 0.58rem;
    text-align: left;
    line-height: 0.24rem;
  }
}
</style>

效果图

在这里插入图片描述

到此这篇关于Vue3使用vue-qrcode-reader实现扫码绑定设备功能的文章就介绍到这了,更多相关Vue3扫码绑定设备内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Vuejs实现购物车功能

    Vuejs实现购物车功能

    这篇文章主要为大家详细介绍了Vuejs实现购物车功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-11-11
  • Vue项目接入Paypal实现示例详解

    Vue项目接入Paypal实现示例详解

    这篇文章主要介绍了Vue项目接入Paypal实现示例详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-06-06
  • vue子组件设计provide和inject理解使用

    vue子组件设计provide和inject理解使用

    这篇文章主要为大家介绍了vue子组件设计provide和inject理解及使用示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-08-08
  • vue子组件通过.sync修饰符修改props属性方式

    vue子组件通过.sync修饰符修改props属性方式

    这篇文章主要介绍了vue子组件通过.sync修饰符修改props属性方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-08-08
  • Vue.js 60分钟轻松入门

    Vue.js 60分钟轻松入门

    Vue.js提供了简洁、易于理解的API,帮助大家快速灵活掌握Vue.js。这篇文章主要介绍了如何在60分钟内轻松学习Vue.js,感兴趣的小伙伴们可以参考一下
    2016-11-11
  • Vue封装DateRangePicker组件流程详细介绍

    Vue封装DateRangePicker组件流程详细介绍

    在后端管理项目中使用vue来进行前端项目的开发,但我们都知道Vue实际上无法监听由第三方插件所引起的数据变化。也无法获得JQuery这样的js框架对元素值的修改的。而日期控件daterangepicker又基于JQuery来实现的
    2022-11-11
  • vue学习笔记之v-if和v-show的区别

    vue学习笔记之v-if和v-show的区别

    本篇文章主要介绍了vue学习笔记之v-if和v-show的区别,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-09-09
  • 一次前端Vue项目国际化解决方案的实战记录

    一次前端Vue项目国际化解决方案的实战记录

    这篇文章主要给大家介绍了关于前端Vue项目国际化解决方案的实战记录,以上只是一部分Vue项目开发中遇到的典型问题和解决方案,文中通过代码介绍的非常详细,需要的朋友可以参考下
    2024-07-07
  • Vue实现导航栏菜单

    Vue实现导航栏菜单

    这篇文章主要为大家详细介绍了Vue实现导航栏菜单,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2020-08-08
  • 解决父子组件通信的三种Vue插槽

    解决父子组件通信的三种Vue插槽

    这篇文章主要为大家介绍了Vue插槽解决父子组件通信,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
    2021-11-11

最新评论