使用生成條形碼并打印和vue-print-nb以及報錯問題的解決
更新時間:2025年07月27日 15:00:00 作者:胡亂更法
在TypeScript項目中,正確安裝vue3-print-nb并配置env.d.ts聲明模塊,添加tsconfig.json的include路徑,確保全局掛載以實現條形碼和批量打印功能
生成條形碼并打印和vue-print-nb以及報錯
借鑒網上大多數vue-print-nb安裝打印,發(fā)現在自己的項目(ts語法下)中會發(fā)現模塊引入錯誤
所以換成
npm install vue3-print-nb //重新安裝
vue-print-nb在自己的項目中無法使用,故此更換
引入后需要在根目錄下的env.d.ts中引入
declare module 'vue3-print-nb' {
const install: (app: App) => void
const print: (options?: PrintOptions) => void
export default { install, print }
}引入后需要在tsconfig.json文件里的include中添加env.d.ts的路徑
也可以在ts項目下的默認下的types下的文件中引入也可以,或者全局搜索 declare module,在添加,這在樣mian.ts下引入 import print from 'vue3-print-nb' 不會報類型報錯,在進行全局掛載
使用條形碼多批量打印
<div class="preview-area" id="printTest">
<div v-for="(item, index) in data" :key="index">
<svg :ref="el => setBarcodeRef(el, index)"></svg>
<p style="page-break-after: always"></p>
</div>
</div>
<el-button v-print="printObj" ref="printBtn" style="display: none;"></el-button>
</div>
const data = ref([])
const barcodeRefs = ref([])
const printBtn = ref(null)
const printObj = reactive({
id: 'printTest',
beforeOpenCallback(vue) {
vue.printLoading = true
},
openCallback(vue) {
vue.printLoading = false
},
closeCallback(vue) {
console.log('關閉了打印工具')
}
})
//獲取每一個對應的svg
const setBarcodeRef = (el, index) => {
barcodeRefs.value[index] = el
}
//list為數據源 調用showPrint進行數據調用
const showPrint = async (list) => {
data.value = list
await nextTick()
await generateBarcode(list)
// 生成完成后自動觸發(fā)打印
await nextTick()
printBtn.value.$el.click()
}
const generateBarcode = async (list) => {
try {
list.forEach((item, index) => {
if(barcodeRefs.value[index]) {
JsBarcode(barcodeRefs.value[index], item.LocationCode, {
format: "CODE128",
lineColor: "#000",
width: 2,
height: 60,
displayValue: true,
fontSize: 16,
margin: 10
});
}
})
} catch (error) {
console.error('生成條形碼失敗:', error);
}
};總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

