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>
相关推荐
还是鼠鼠20 分钟前
图书管理系统 Axios 源码__新增图书
前端·javascript·vscode·ajax·前端框架·node.js·bootstrap
customer081 小时前
【开源免费】基于SpringBoot+Vue.JS体育馆管理系统(JAVA毕业设计)
java·vue.js·spring boot·后端·开源
还是鼠鼠3 小时前
图书管理系统 Axios 源码 __删除图书功能
前端·javascript·vscode·ajax·前端框架·node.js·bootstrap
轻口味4 小时前
Vue.js `Suspense` 和异步组件加载
前端·javascript·vue.js
m0_zj5 小时前
8.[前端开发-CSS]Day08-图形-字体-字体图标-元素定位
前端·css
还是鼠鼠5 小时前
图书管理系统 Axios 源码__编辑图书
前端·javascript·vscode·ajax·前端框架
北极象5 小时前
vue3中el-input无法获得焦点的问题
前端·javascript·vue.js
百度网站快速收录5 小时前
网站快速收录:如何优化网站头部与底部信息?
前端·html·百度快速收录·网站快速收录
Loong_DQX6 小时前
【react+redux】 react使用redux相关内容
前端·react.js·前端框架
GISer_Jing6 小时前
react redux监测值的变化
前端·javascript·react.js