<!--强哥的自定义组件:H5唤起微信“扫一扫”-->
<template><div class="sg-scan" :up="isToUp"><van-button icon="scan" type="info" @click="scan" round /></div>
</template>
<script>
// import wx from "weixin-jsapi"; //这个快要被废弃了1.0.0
import wx from "weixin-js-sdk"; //要用微信的屌方法必须要引入这个玩意儿!!!
export default {data() {return {isToUp: false,defaultScanErrorText: "该码不属于本系统,暂不支持识别!"};},/* 【属性说明】 (均为非必须参数)onlyScanWeb:true/false 是否仅支持识别网址(默认false)containString:" " 识别内容必须包含字符串内容(一般用于限定xxx.com域名下的内容)scanErrorText:" " 识别失败后的错误提示文本内容autoLink:true/false 是否自动跳转识别的路径(默认false)*/props: ["onlyScanWeb", "containString", "scanErrorText", "autoLink"],mounted() {this.initScroll();},methods: {//顶部导航条(菜单)随着滚动条隐藏:1、滚动条往下隐藏导航条;2、滚动条往上显示导航条initScroll() {var beforeScrollTop =window.pageYOffset ||document.documentElement.scrollTop ||document.body.scrollTop ||0;onscroll = () => {var afterScrollTop =window.pageYOffset ||document.documentElement.scrollTop ||document.body.scrollTop ||0;this.isToUp = afterScrollTop > beforeScrollTop;beforeScrollTop = afterScrollTop;};},scan(callback) {wx.ready(() => {//注意!!!一定要在wx.config的jsApiList: []数组中加入"scanQRCode",否则你怎么死的都不知道wx.scanQRCode({needResult: 1, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果,scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码,默认二者都有success: res => {/* 【返回结果】res:{"resultStr":"二维码识别内容(可能是链接或者文本内容)","errMsg":"scanQRCdoe:ok",} */var result = res.resultStr; // 当needResult 为 1 时,扫码返回的结果if (this.onlyScanWeb !== undefined && this.onlyScanWeb !== false) {if (result.indexOf("http") !== 0) return this.errorTip();}if (this.containString) {if (!result.includes(this.containString)) return this.errorTip();}this.autoLink !== undefined &&this.autoLink !== false &&location.replace(result); //自动跳转链接this.$emit("scan", result); //触发父文件绑定的scan事件,并抛出扫码识别的内容callback && typeof callback === "function" && callback(result); //执行回调函数(通常用于父组件调用this.$refs.sgScan.scan(d=>{}))}});});},errorTip() {var text = this.scanErrorText || this.defaultScanErrorText;this.$notify({ message: text });alert(text); //千万不要用Vant组件的dialog、toast等弹窗提示,否则你什么也看不到,会让微信扫一扫界面闪退}}
};
</script>
<style lang="scss" scoped>
@import "~@/css/sg";
.sg-scan {@extend %transition;position: fixed;width: 80px;margin: auto;left: 0;right: 0;bottom: 50px;text-align: center;&[up] {bottom: -80px;}.van-button {width: 80px;height: 80px;font-size: 2rem;box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);}
}
</style>