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>
相关推荐
雾恋1 小时前
最近一年的感悟
前端·javascript·程序员
华仔啊1 小时前
Vue3 的 ref 和 reactive 到底用哪个?90% 的开发者都选错了
javascript·vue.js
A黄俊辉A1 小时前
axios+ts封装
开发语言·前端·javascript
小李小李不讲道理2 小时前
「Ant Design 组件库探索」四:Input组件
前端·javascript·react.js
连合机器人2 小时前
晨曦中的守望者:当科技为景区赋予温度
java·前端·科技
郑板桥303 小时前
tua-body-scroll-lock踩坑记录
前端·javascript
IT古董3 小时前
Vue + Vite + Element UI 实现动态主题切换:基于 :root + SCSS 变量的最佳实践
vue.js·ui·scss
解道Jdon3 小时前
SpringBoot4与Spring7发布:云原生深度进化
javascript·reactjs
慢半拍iii4 小时前
JAVA Web —— A / 网页开发基础
前端
gnip4 小时前
pnpm 的 monorepo架构多包管理
前端·javascript