实现的效果:

JsBarcode

自己写的代码:


<template>
  <div class="container">
    <div class="content">JsBarcode</div>
    <svg id="barcode"></svg>
  </div>
</template>

<script>
import JsBarcode from "jsbarcode";
export default {
  name: "XuexiKuangjiaJsbarcode",

  data() {
    return {};
  },

  mounted() {
    this.getBarcode();
  },

  methods: {
    getBarcode() {
      let options = {
        text: "123456789",
        displayValue: true,
        fontSize: 12,
        height: 40,
        // width: 1,
      };
      this.$nextTick(() => {
        JsBarcode("#barcode", "987654321", options);
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  .content {
    background-color: aquamarine;
    font-size: 20px;
  }
}
</style>


一、JsBarcode介绍

JsBarcode是:一个用JavaScript编写的条形码生成器。 它支持多种条形码格式,可在浏览器和Node.js中使用。

JsBarcode 官网

二、JsBarcode安装

在对应项目的终端中,输入如下代码,安装

npm install jsbarcode --save

三、页面引入使用

3.1 在二维码生成的页面中引入

import JsBarcode from "jsbarcode";

3.2 二维码生成的容器

在前面例子中 使用 <svg></svg>这个容器的。
二维码的容器有三个:

<canvas id="canvas"></canvas>
<img id="barcode"/>
<svg id="barcode"></svg>

3.3 生成二维码
可以将生成的条形码放在一个方法里面:

    getBarcode() {
      let options = {
        text: "123456789", 
        displayValue: true,
        fontSize: 12,
        height: 40,
        width: 1,
      };
      this.$nextTick(() => { //这个根据自己的代码 论情况写
        JsBarcode("#barcode", "987654321", options); 
        //#barcode 对应容器中的id
        //987654321 是条形码的携带的信息,和option中的text显示信息要区分
        //options:是条形码的配置信息
      });
    },

3.4 options 配置选择项

option 默认值 类型 备注
format “auto” (CODE128) String 控制条形码的类型
width 2 Number 每个条条的宽度,注意这里不是指整个条形码的宽度
height 100 Number 整个条形码的宽度
displayValue true Boolean 是否在条形码下面显示文字
fontOptions “ ” string 设置条形码文本的粗体和斜体样式 bold / italic / bold italic
font “monospace” String 设置条形码显示文本的字体
textAlign “center” String 条形码文本的水平对齐方式,和css中的类似: left / center / right
textPosition bottom String 条形码文本的位置 bottom / top
textMargin 2 Number 条形码文本 和 条形码之间的间隙大小
fontSize 20 Number 设置条形码文本的字体大小
background “#ffffff” String (CSS color) 整个条形码容器的背景颜色
lineColor “#000000” String (CSS color) 条形码和文本的颜色
margin 10 Number 整个条形码的外面距
marginTop undefined Number
marginBottom undefined Number
marginLeft undefined Number
marginRight undefined Number
valid function (valid){} function 执行完条形码的一个回调函数,正确true 错误false

根据上述options 举例
举例

在HTML中申明options:
注意:这里条形码的类型是 upc 也要注意 value的格式 否则条形码会报错
在html中 申明options

四、存在的问题:

1、条形码总体的宽度,我现在只有调节每条的宽度来调节;
2、条形码的宽高生成就定好了,如果外面有个容器的话,条形码会超出外面的容器显示,影响布局,比如在flex 布局下的条形码。
Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐