1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
| <template>
| <img :src="qrCodeUrl" alt="" srcset="" style="width: 100%; height: 100%;" />
| </template>
|
| <script lang="ts">
| import { onMounted, reactive, toRefs, watch } from "vue";
| import QrCode from "qrcode";
| export default {
| name: "QrCode",
| props: {
| width: {
| type: Number,
| default: 200,
| },
| height: {
| type: Number,
| default: 200,
| },
| colorDark: {
| type: String,
| default: "#000000",
| },
| colorLight: {
| type: String,
| default: "#ffffff",
| },
| margin: {
| type: Number,
| default: 4,
| },
| value: {
| type: Object,
| },
| },
| setup(props, contxt) {
| let debounceTimer: any;
| const state = reactive({
| qrCodeUrl: "",
| });
|
| watch(
| () => props.value,
| () => {
| console.log('二维码触发了')
| debounceTimer && clearTimeout(debounceTimer);
| debounceTimer = setTimeout(generateQRCode, 500);
| }, { deep: true }
| );
|
| /** 生成二维码 */
| const generateQRCode = () => {
| if (!props.value) {
| state.qrCodeUrl = "";
| contxt.emit("error", { message: "二维码内容为空" });
| return;
| }
| const options = {
| width: props.width,
| height: props.height,
| margin: props.margin,
| color: {
| dark: props.colorDark,
| light: props.colorLight,
| },
| };
| QrCode.toDataURL(JSON.stringify(props.value), options, (error, url) => {
| if (error) {
| console.error("二维码生成失败: ", error);
| contxt.emit("error", { message: "二维码生成失败" });
| return;
| }
| state.qrCodeUrl = url;
| });
| };
|
| onMounted(() => {
| generateQRCode();
| })
|
| return {
| ...toRefs(state),
| generateQRCode,
| };
| },
| };
| </script>
|
| <style lang="less" scoped>
| </style>
|
|