? 最近在做一個移動端的項目,里邊有一個需求是生成鏈接并且同時把鏈接轉換成二維碼的需求,效果圖如下:
涉及到隱私,打個碼
因為用的是vue框架,而且是第一次做這中需求的東西,于是果斷百度了一波,出來了一堆 什么qrcodejs2各種各樣的,一幫人抄來抄去,能不能親自試完了再抄啊?害我挨個爬坑。這里就給大家分享幾個簡單易懂用起來得勁的!
如果你的項目需求單純的只是需要將鏈接轉換成二維碼的話,這里比較好用的推薦?"@xkeshi/vue-qrcode"插件;
用法如下:
第一步:安裝@xkeshi/vue-qrcode.js包
npm install --save @xkeshi/vue-qrcode? ? ? //安裝到生產環境
第二步:組件中使用
template
<div class="qrcodeBox">
? ? ? ? ?<qrcode? :value="xxx" v-if="xxx"></qrcode>?
? ? ? ? ?<!--? v-if="xxx"是為了防止鏈接沒獲取到顯示空白,確保獲取到鏈接后才開始渲染 -->
</div>
script
import Qrcode from "@xkeshi/vue-qrcode";? ?//引入
data(){
? ? ?xxx:" "? ? ? ? ? ?//獲取到的鏈接
}
//注冊生成二維碼組件
components: {
? ? qrcode: Qrcode
? },
methods:{
}
這樣是不是很簡單?只要xxx的轉換,二維碼就會自動更新,不需要進行過多的操作。
如果給你的需求不僅僅是生成二維碼這么簡單,還需要在移動端實現長按保存那么就得換另外一種了,下邊為大家來介紹qrcode.js;
QRCode.js
QRCode.js 是一個用于生成二維碼的 JavaScript 庫。主要是通過獲取 DOM 的標簽,再通過 HTML5 Canvas 繪制而成,不依賴任何庫。
基本用法
html
<div id="qrcode"></div>
script
<script type="text/javascript">
? // 設置要生成二維碼的鏈接
? ? ? new QRCode(document.getElementById("qrcode"), "http://www.runoob.com");
</script>
或者使用一些可選參數設置:
var qrcode=new QRCode("qrcode",{
? ? ? text: "http://baidu.com",
? ? ? width:120,
? ? ? height:120,
? ? ? coloeDark:"#000000",
? ? ? coloeLight:"#ffffff",
? ? ? correctLevel:"QRCode.CorrectLevel.H"
? ?})
同樣我們可以使用以下方法:
qrcode.clear(); // 清除代碼
qrcode.makeCode("http://www.w3cschool.cc"); // 生成另外一個二維碼
瀏覽器支持
支持該庫的瀏覽器有:IE6~10, Chrome, Firefox, Safari, Opera, Mobile Safari, Android, Windows Mobile, 等,兼容性強。
那么在vue中怎么使用呢?
第一步:安裝qrcode.js包
npm install qrcode --save-dev
第二步:在vue中引入
import QRCode from 'qrcode';//如果有很多頁面使用的話可以在main中引入,掛載在全局;
template
<div id="code">
? ? ? ? ? ?<canvas id="canvas" ></canvas>
? </div>
script
? ?components:? {
? ? ? ? QRcode:QRCode? ? ?//注冊組件
? ? }
methods:{
? ? getUrl(xxx){
? ? ? ? var canvas=document.getElementById("canvas"); //獲取到canvas
? ? ? ? var code=document.getElementById("code");? ?//獲取到code容器
? ? ? ? QRCode.toCanvas(canvas,xxx, error=> {
? ? ? ? ? ? if (error) console.error(error);
? ? ? ? ? ? ?console.log("success!");
? ? ? ? ? ? ? });
? ? ? ? ? var image = new Image();? ? ?//實例一個img
? ? ? ? ? image.src = canvas.toDataURL("image/png");? //轉換成base64格式路徑的png圖片?
? ? ? ? ? image.style.width = "100%";? ? //設置樣式
? ? ? ? ? code.appendChild(image);? ? ?//添加到code 容器中
? ? ? ? ? canvas.style.display = "none";? ?//隱藏掉canvas??
? ?}
}
mounted(){
? ? ? var xxx="www.baidu.com";
? ? ? this.getUrl(xxx);
}
在這里用到的思路其實就是將鏈接先轉換成二維碼,然后再用canvas調用toDataURL()的方法得到以base64編碼的url,然后用img標簽加載出來,至于為什么非得轉換成圖片呢?這就是利用了圖片在移動端瀏覽器中或者微信中都是有自帶的長按響應事件的,當你長按對象是圖片的話就會提示你保存圖片,下附效果圖:
在這里提醒大家,以后從網上找東西的時候一定要自己多去嘗試一下,切記!