vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > 生成条形码并打印和vue-print-nb及报错

使用生成条形码并打印和vue-print-nb以及报错问题的解决

作者:胡乱更法

在TypeScript项目中,正确安装vue3-print-nb并配置env.d.ts声明模块,添加tsconfig.json的include路径,确保全局挂载以实现条形码和批量打印功能

生成条形码并打印和vue-print-nb以及报错

借鉴网上大多数vue-print-nb安装打印,发现在自己的项目(ts语法下)中会发现模块引入错误

所以换成    

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)
    // 生成完成后自动触发打印
    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);
    }
};

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文