vue生成二維碼:vue-qr二維碼外掛使用
阿新 • • 發佈:2021-06-18
1.下載 qrcode
npm i qrcode
2.在所需元件使用qrcode
<template>
<div>
<img :src="qrcode" width="192">
</div>
</template>>
import QRCode from 'qrcode'
export default{
data(){
return{
qrcode:''
}
},
mounted(){
this.setQRCode('http:xxx.xx')
},
methods:{
// 根據字串生成二維碼
setQRCode(str) {
QRCode.toDataURL(str, { width: 192, margin: 1 }).then(res=>{
// toDataURL方法返回一個promise
this.qrcode = res;
})
}
}
}
接下來就具體看一下qrcode的其他使用方法:
qrcode 指南
方法
下面方法的引數中
opts
和回撥函式cb
都是可選項,不是必填引數
瀏覽器
只支援前四個方法,伺服器可以支援以下全部方法
1.create(text, opts)
QRCode.create("str")
// 返回結果為物件
// {
// modules, // 具有模組資料的Bitmatrix類
// version, // 版本
// errorCorrectionLevel, // 糾錯級別
// maskPattern, // 計算後的遮罩圖案
// segments // segments
// }
2.toCanvas(canvas, text, opts)
<canvas id="canvas"></canvas>
var canvas = document.getElementById('canvas')
QRCode.toCanvas(canvas, 'str', function (err) {
if (err) console.log(err)
})
3.toDataURL(text, opts, cb)
//此方法是剛開始例子的nodejs寫法,這裡的回撥函式引數不同
QRCode.toDataURL("str", (err, res) => {
// 注意這裡第一個引數是err,第二個引數才是二維碼圖片連結
this.qrcode = res;
});
4.toString(text, opts, cb)
<div v-html="qrcode" style="width:192px"></div>
QRCode.toDataURL("str", (err, res) => {
// 注意這裡的res結果是一個svg圖片
this.qrcode = res;
});
5.toFile(path, text, opts, cb)
// 這個方法試了沒成功,暫存一下
QRCode.toFile("path/filename.png", "str", err => {
if (err) throw err;
});
6.toFileStream(stream, text, opts)
7.toBuffer(text, opts, cb)
配置引數 opts
margin
作用: 二維碼線條到整個圖片邊緣的距離,類似前端的padding
型別:Number
預設: 4
scale
作用: 比例,比如上面的margin為4px,實際上為16px.
型別:Number
預設: 4
width
作用: 生成二維碼圖片的寬度
型別:Number
預設: 116
color.dark
作用: 二維碼線條的顏色
型別:String
預設: '#000'
color.light
作用: 二維碼背景色
型別:String
預設: '#fff'