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>