最近,公司项目中使用的条形码与二维码,经过百度网上基本给的都是单个条形码与二维码的使用,没有找到如何渲染一个列表的demo,那么下面将讲解如何在vue中渲染一个条形码列表:
第一步: npm intall jsbarcode --save
第二步:在需要使用的页面引入:import JsBarcode from 'jsbarcode'
第三步:在循环一个列表中使用:
<div v-for="(site,index) in list" :key="index>
<p>条形码:{{index}}</p>
<img :id="'barcode'+index" :ref="'barcode'+index"/>
</div>
//重点js如何渲染
data(){
return{
list:[]
}
},
mounted(){
//首先请求获取列表
this.getData();
},
methods:{
getData(){
//如果刷新重新生成条形码会发现一直叠加,因此在生成前需要清空原先列表
this.list = [];
getList().then((res)=>{
this.list = data;
//很重要接下来这一步 必须dom渲染完成才能形成二维码,否则报没有发现appendChild
this.$nextTick(function(){
for(let [index,value] of this.list.entries()){
this.qrcodeOrder(index,value)
}
})
})
},
qrcodeOrder(index,value) {
let dom = this.$refs['barcode'+index][0];
JsBarcode(dom, "Smallest width",{
format: "CODE128",
text:index,//条形码值值
displayValue: false,
margin:0,
})
},
}
具体options https://github.com/lindell/JsBarcode
下面是二维码生成demo;
第一步:npm install qrcodejs2 --save
第二步:mport QRCode from 'qrcodejs2'
第三步:
<div v-for="(site,index) in list">
<div :id="'record_'+index" :ref="'record_'+index"></div>
</div>
data(){
return{
list:[]
}
},
methos:{
billSalesRequest(){//获取出货单
printAllOrder(this.paramsList).then((res)=>{
this.list = res.data;
this.$nextTick(function(){
for(let [index,value] of this.list.entries()){
this.qrcodeOrder(index,value)
}
})
this.dataloading = false;
}).catch((err)=>{
this.dataloading = false;
})
},
qrcodeOrder(index,value) {
let dom = this.$refs['record_'+index][0];
let qrcode = new QRCode(dom, {
width: 120,
height: 120,
text:value.orderid
)
},
}
具体option:https://github.com/KeeeX/qrcodejs
其实,jsbarcode,qrcodejs2在vue中使用原理都相同,码生成之前必须挂载dom生成,否则会报没有发现dom
注意事项:
1.必须等dom挂载完在调用
2.在updated 生命周期中调用,会造成不断更新,结果码重复添加
3.刷新查询,要清空之前的码,我使用的是直接清空列表数据,当然你可以使用文档指定方法,原理一样
4.如果异步请求必须按上述步骤来,异步会导致挂载码失败
5.以上是自己在工作中总结的,如有问题请留言。