这是一个自己封装的组件
市面上还有其他组件:
vue-qr :这个可以给二维码中间加图片
本次封装组件的实例图如下:
下载qrcodde
npm i qrcode -S
下载复制的插件
npm i vue-clipboard2 -S
QRcode.vue组件
<comment>
# 组件注释
这是一个公用组件
v-clipboard:下载的一个插件
</comment>
<template>
<div id="QRCode" :style="{'width':width, 'height':height}">
<canvas :id="canvasId" :style="{'width':width, 'height':height}"></canvas>
<div class="flex jc-center">
<el-button
type="text"
v-if="copy"
v-clipboard:copy="content"
v-clipboard:success="onCopy"
v-clipboard:error="onError"
>复制链接</el-button>
<el-button class="configBtn" type="text" size="" @click="download" v-if="download">下载二维码</el-button>
</div>
</div>
</template>
<script>
import QRCode from "qrcode";
import VueClipboard from "vue-clipboard2";
export default {
name: "QRCode",
props: {
canvasId: {
type: String,
default: "canvasId"
},
content: {// 二维码中存储的信息
type: String,
default: "测试二维码"
},
width: {
type: String,
default: "200"
},
height: {
type: String,
default: "200"
},
download: {
type: Boolean,
default: false
},
copy: {
type: Boolean,
default: false
},
downloadParam: { // 下载的参数
type: Object,
default() {
return {
width: 200,
height: 200,
name: "二维码" // 下载之后的文件名
};
}
},
view: {
type: Boolean,
default: true
}
},
data() {
return {};
},
computed: {},
created() {
this.$nextTick(() => {
this.init();
});
},
mounted() {},
methods: {
init() {
let width = this.width,
height = this.height;
QRCode.toCanvas(
document.getElementById(this.canvasId),
this.content,
{ width, height, toSJISFunc: QRCode.toSJIS },
error => {}
);
},
onCopy: function(e) {
this.$message({
message: `复制成功!`,
type: "success"
});
},
onError: function(e) {
alert("复制失败");
},
// 下载二维码
download() {
const ele = document.createElement("canvas");
ele.style.width = this.downloadParam.width || "200" + "px";
ele.style.height = this.downloadParam.height || "200" + "px";
QRCode.toCanvas(
ele,
this.content,
{
width: this.downloadParam.width || "200",
height: this.downloadParam.height || "200",
toSJISFunc: QRCode.toSJIS
},
error => {}
);
let [F, S, a] = [
navigator.userAgent.indexOf("Firefox") > -1,
ele.toDataURL("image/png"),
document.createElement("a")
];
[a.href, a.download] = [S, this.downloadParam.name];
if (F) {
let evt = document.createEvent("MouseEvents");
evt.initEvent("click", true, true);
a.dispatchEvent(evt);
} else {
a.click();
}
}
},
watch: {
content(val) {
this.init();
}
}
};
</script>
<style lang="scss" scoped>
#QRCode {
display: inline-block;
position: relative;
overflow: hidden;
}
</style>
使用上面的组件生成二维码
<template>
<div id="QRcode_gr">
<QRcode
width="200"
height="200"
:content="content"
:load="true"
:copy="false"
:downloadParam="{width: 200,
height: 200,
name: '二维码'}"
></QRcode>
</div>
</template>
<script>
import QRcode from "@/components/common/QRcode";
export default {
name: '',
components: {QRcode },
props: {},
data() {
return {
content: 'www.baidu.com',
name: ''
}
},
watch: {},
computed: {},
created() { },
mounted() { },
methods: {
},
destroyed() { }
}
</script>
<style lang='scss'>
</style>