[web前端] 浏览端生成二维码

环境准备

安装生成二维码依赖

npm i qrcodejs2

封装二维码生成组件

<template>
    <div class="qr-code-comp-container">
        <div :ref="id" class="qr-code"></div>
        <div class="text">{{ text }}</div>
    </div>
</template>

<script>
import QRCode from "qrcodejs2";
export default {
    name: "QrCodeComp",
    data() {
        return {
            qrcode: null,
        };
    },
    props: {
        id: {
            type: String,
            required: true,
        },
        text: {
            type: String,
            default: "",
        },
        width: {
            type: String,
            default: "128",
        },
        height: {
            type: String,
            default: "128",
        },
        colorDark: {
            type: String,
            default: "#000000",
        },
        colorLight: {
            type: String,
            default: "#ffffff",
        },
    },
    mounted() {
        this.createQrcode();
    },
    methods: {
        createQrcode() {
            if (this.qrcode) {
                this.qrcode.clear(); // 清除二维码方法二
            }
            this.qrcode = new QRCode(this.$refs[this.id], {
                text: this.text, //页面地址 ,如果页面需要参数传递请注意哈希模式#
                width: this.width, // 二维码宽度 (不支持100%)
                height: this.height, // 二维码高度 (不支持100%)
                colorDark: this.colorDark, // 调整二维码的背景颜色
                colorLight: this.colorLight,
                correctLevel: QRCode.CorrectLevel.H,
            });
        },
    },
};
</script>

<style scoped>
.qr-code-comp-container {
    height: 200px;
    width: 200px;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.qr-code {
    width: 128px;
    height: 128px;
}

.text {
    margin-top: 10px;
    height: 30px;
    width: 100%;
    text-align: center;
    line-height: 30px;
}
</style>

父组件调用封装好的二维码组件

<template>
    <div class="code-list-container">
        <QrCodeComp v-for="item in textList" :key="item.id" :id="item.id" :text="item.text"></QrCodeComp>
    </div>
</template>

<script>
import QrCodeComp from "./QrCodeComp.vue";
export default {
    name: "CodeList", // 列表二维码测试
    data() {
        return {
            textList: [],
        };
    },
    created() {
        let tmpArr = [];
        for (let i = 0; i < 50; i++) {
            tmpArr.push({
                id: `${i}`,
                text: `测试${i}`,
            });
        }
        this.textList = tmpArr;
    },
    components: {
        QrCodeComp,
    },
};
</script>

<style>
.code-list-container {
    display: grid;
    grid-template-columns: repeat(3, 250px);
}
</style>

打印预览效果

在这里插入图片描述

查询dom 元素

在这里插入图片描述
可以看到这里把二维码图片进行了 base64 编码, 在页面上进行了展示。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值