springboot+vue生成二维码
时间: 2023-10-04 14:13:40 浏览: 137
生成二维码可以使用zxing库,而在Spring Boot中集成zxing可以使用springfox依赖。
1. 添加依赖
在pom.xml文件中添加以下依赖:
```xml
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.3</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.3</version>
</dependency>
```
2. 添加二维码生成接口
在Controller中添加以下接口:
```java
@RestController
@RequestMapping("/api")
@Api(tags = "二维码生成接口")
public class QRCodeController {
@GetMapping("/qrcode/{content}")
@ApiOperation(value = "生成二维码", notes = "根据传入的内容生成二维码")
public void generateQRCode(@PathVariable String content, HttpServletResponse response) {
try {
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, 200, 200);
MatrixToImageWriter.writeToStream(bitMatrix, "png", response.getOutputStream());
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
3. 访问接口
启动Spring Boot应用后,在浏览器中访问http://localhost:8080/swagger-ui.html,可以看到Swagger UI界面,找到“二维码生成接口”并点击“Try it out”,输入需要生成二维码的内容,点击“Execute”,就可以生成二维码了。
4. 在Vue中使用
在Vue组件中添加以下代码:
```html
<template>
<div>
<button @click="generateQRCode">生成二维码</button>
<img :src="qrcode" v-if="qrcode">
</div>
</template>
<script>
export default {
data () {
return {
qrcode: null
}
},
methods: {
generateQRCode () {
const content = 'https://www.baidu.com' // 需要生成二维码的内容
this.qrcode = `http://localhost:8080/api/qrcode/${encodeURIComponent(content)}`
}
}
}
</script>
```
在按钮点击事件中,使用axios发送GET请求获取生成的二维码图片地址,然后在img标签中显示即可。需要注意的是,需要使用encodeURIComponent对内容进行编码,以防止特殊字符造成问题。
阅读全文
相关推荐

















