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>
相关推荐
IT_陈寒11 小时前
Vite热更新失效?你可能漏了这个配置
前端·人工智能·后端
Revolution6112 小时前
React 组件重新渲染时,到底重新执行了什么
前端·react.js·面试
林焱_RPAAI12 小时前
影刀RPA技术深度:CSS选择器高级实战指南——伪类属性选择器与性能对比完全解析
vue.js·react.js
用户21816970493013 小时前
Flutter(四)Dart语法 空安全 运算符 流程控制
前端
许彰午13 小时前
政务督办的分合模式:主办协办的并发审批
前端·javascript·政务
用户693717500138413 小时前
AI时代,程序员该往哪走?
前端·后端
陳陈陳13 小时前
🚀 前端流式输出革命:SSE + BFF 架构从零到一实战指南
vue.js·架构·node.js
ttwuai13 小时前
GoFrame 后台日志清空失败:无 WHERE 删除为什么被拦住
前端·golang
易筋紫容14 小时前
创建型模式:对象的诞生艺术
开发语言·前端·javascript
半句唐诗14 小时前
我是如何通过 Access Token 成功发布第一个 npm 包的
前端·npm·node.js