vue+jsbarcode实现条码预览功能

bash 复制代码
npm install jsbarcode
html 复制代码
<template>  
    <div>  
        <div v-for="(barcodeData, index) in barcodeDataArray" :key="index">  
            <svg :id="'barcode' + index" :data-barcode="barcodeData.value"></svg>  
            <p class="barcode-value">{{ barcodeData.value }}</p>  
        </div>  
        <button @click="add">添加一个二维码</button>
    </div>  
</template>  
  
<script setup>  
import { onMounted, reactive, nextTick  } from 'vue';  
import JsBarcode from 'jsbarcode';  
  
// 使用 reactive 创建一个响应式对象来存储条形码数据数组  
const barcodeDataArray = reactive([
    { value: '1000172664' },  
    { value: '1000172665' },  
    // ... 添加更多条形码数据  
]);  
function add(){
    barcodeDataArray.push({value: '1000172669'})
    console.log(barcodeDataArray);
    const lastIndex = barcodeDataArray.length - 1; // 获取最新添加的数据的索引  
    const svgId = 'barcode' + lastIndex; // 构造 SVG 的 ID  
    console.log(svgId,barcodeDataArray[lastIndex].value);
    nextTick(() => { 
    JsBarcode(`#${svgId}`, barcodeDataArray[lastIndex].value, {  // 使用最新的数据来渲染  
        format: "CODE128",  
        width: 4,  
        height: 200,  
        displayValue: false,  
        textPosition: "bottom",  
        background: "#fff",  
        lineColor: "#000",  
        fontSize: 14,  
        margin: 8  
    });  
    });
}

onMounted(() => {  
    // 使用 nextTick 确保 DOM 更新后再渲染条形码  
    nextTick(() => {  
        barcodeDataArray.forEach((barcodeData, index) => {  
            const svgId = 'barcode' + index;  
            console.log(svgId);
            JsBarcode(`#${svgId}`, barcodeData.value, {  
                format: "CODE128",  
                width: 4,  
                height: 200,  
                displayValue: true,  
                textPosition: "bottom",  
                background: "#fff",  
                lineColor: "#000",  
                fontSize: 14,  
                margin: 8  
            });  
        });  
    });  
});  
</script>  
  
<style scoped>  
/* 你的样式 */  
</style>
相关推荐
XiYang-DING21 小时前
HTML 核心标签
前端·html
Csvn1 天前
技术选型方法论
前端
Csvn1 天前
前端架构演进:从页面到平台的十年变革
前端
李伟_Li慢慢1 天前
ShaderToy-山峦+蓝天+白云
前端·webgl
小码哥_常1 天前
Android字体字重设置全攻略:XML黑科技+Kotlin动态实现,告别.ttf臃肿
前端
FYKJ_20101 天前
springboot校园兼职平台--附源码02041
java·javascript·spring boot·python·eclipse·django·php
言萧凡_CookieBoty1 天前
AI 编程省 Token 实战:从 Spec、上下文工程到模型分层的降本策略
前端·ai编程
DFT计算杂谈1 天前
wannier90 参数详解大全
java·前端·css·html·css3
铁皮饭盒1 天前
第2课:5分钟!用 Trae AI 生成你的第一个后端服务(Bunjs + Elysia)
前端·后端·全栈