使用vue2做一个生成二维码的案例【可当组件使用】

0 阅读1分钟

最近有个需求需要用前端来生成一个二维码,就封装了一个简单的组件,这篇文章来分享给大家。
使用的技术:

Vue2

Ant Design Vue

QRCodeJS2

node版本:16.20

组件样式:

image.png

大家可以根据自己的需求来调整代码。

image.png

依赖安装:

npm i

项目启动:

npm run serve

调用页面代码:

<template>
  <div id="app">
    <div class="container">
      <a-card title="二维码生成示例" style="width: 500px">
        <a-input
          v-model="qrContent"
          placeholder="请输入二维码内容"
          style="margin-bottom: 10px"
        />
        <a-input
          v-model="qrText"
          placeholder="请输入二维码说明文字"
          style="margin-bottom: 10px"
        />
        <a-input
          v-model="backgroundColor"
          placeholder="请输入二维码背景色(如:#ffffff)"
          style="margin-bottom: 10px"
        />
        <a-button type="primary" @click="generateQR">生成二维码</a-button>
        <a-divider />
        <QRCode
          v-if="showQR"
          ref="qrCode"
          :value="qrContent"
          :text="qrText"
          :qrSize="300"
          :padding="5"
          :fontSize="18"
          :backgroundColor="backgroundColor"
          textAlign="left"
        ></QRCode>
        <a-button v-if="showQR" type="primary" @click="downloadQR" style="margin-top: 10px">下载二维码</a-button>
      </a-card>
    </div>
  </div>
</template>

<script>
import QRCode from './components/QRCode.vue'

export default {
  name: 'App',
  components: {
    QRCode
  },
  data() {
    return {
      qrContent: '',
      qrText: '',
      backgroundColor: '#ffffff',
      showQR: false
    }
  },
  methods: {
    generateQR() {
      if (!this.qrContent) {
        this.$message.error('请输入二维码内容')
        return
      }
      this.showQR = true
    },
    downloadQR() {
      const qrData = this.$refs.qrCode.getQRCodeData()
      const link = document.createElement('a')
      link.download = 'qrcode.png'
      link.href = qrData
      link.click()
    }
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #2c3e50;
}
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f0f2f5;
}
</style>

组件核心代码:

image.png

这个使用vue2生成二维码的案例 代码 已经整理好了,有需要的小伙伴,可以自行获取使用: wwwoop.com/home/Index/…