Files
hazardousWaste_app/components/BarcodeGenerator.vue

60 lines
1.5 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!-- components/BarcodeGenerator.vue -->
<template>
<div class="barcode-container">
<canvas v-if="type === 'canvas'" ref="barcodeRef"></canvas>
<svg v-else ref="barcodeRef"></svg>
</div>
</template>
<script setup>
import { ref, watch, onMounted, defineProps, defineEmits } from 'vue';
import JsBarcode from 'jsbarcode';
// 定义Props外部传参
const props = defineProps({
value: { // 条形码内容
type: String,
required: true
},
format: { // 条形码格式
type: String,
default: 'CODE128'
},
type: { // 渲染类型
type: String,
default: 'canvas',
validator: (val) => ['canvas', 'svg'].includes(val)
},
options: { // 自定义配置
type: Object,
default: () => ({
width: 2,
height: 100,
displayValue: true
})
}
})
// 定义DOM引用
const barcodeRef = ref(null)
// 生成条形码
const generate = () => {
if (!barcodeRef.value) return
// 合并默认配置和外部配置
const finalOptions = { ...props.options, format: props.format }
// 清空CanvasSVG无需清空
if (props.type === 'canvas') {
const ctx = barcodeRef.value.getContext('2d')
ctx.clearRect(0, 0, barcodeRef.value.width, barcodeRef.value.height)
}
// 生成条形码
JsBarcode(barcodeRef.value, props.value, finalOptions)
}
// 挂载后初始化
onMounted(generate)
// 监听props变化自动更新
watch([() => props.value, () => props.format, () => props.options], generate, { deep: true })
</script>