60 lines
1.5 KiB
Vue
60 lines
1.5 KiB
Vue
<!-- 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 }
|
||
// 清空Canvas(SVG无需清空)
|
||
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> |