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>
相关推荐
前端大卫15 小时前
为什么 React 中的 key 不能用索引?
前端
你的人类朋友15 小时前
【Node】手动归还主线程控制权:解决 Node.js 阻塞的一个思路
前端·后端·node.js
小李小李不讲道理17 小时前
「Ant Design 组件库探索」五:Tabs组件
前端·react.js·ant design
毕设十刻17 小时前
基于Vue的学分预警系统98k51(程序 + 源码 + 数据库 + 调试部署 + 开发环境配置),配套论文文档字数达万字以上,文末可获取,系统界面展示置于文末
前端·数据库·vue.js
mapbar_front18 小时前
在职场生存中如何做个不好惹的人
前端
牧杉-惊蛰18 小时前
纯flex布局来写瀑布流
前端·javascript·css
一袋米扛几楼9819 小时前
【软件安全】什么是XSS(Cross-Site Scripting,跨站脚本)?
前端·安全·xss
向上的车轮19 小时前
Actix Web适合什么类型的Web应用?可以部署 Java 或 .NET 的应用程序?
java·前端·rust·.net
XiaoYu200220 小时前
第1章 核心竞争力和职业规划
前端·面试·程序员
excel20 小时前
🧩 深入浅出讲解:analyzeScriptBindings —— Vue 如何分析 <script> 里的变量绑定
前端