前言

目前公司Vue H5项目,用webview打包成APP,现产品提出这样打包出来的app运行较慢,需要用uniapp方式(即使用HBuilder编辑器来打包H5)来打包,那需要的基座就不是安卓的基座而是uniapp的基座,而H5项目实现手机扫描功能就需要调用uniapp的基座的方法。

具体步骤

一、Uniapp Webview 源码

<template>
<view>
<web-view :webview-styles="webviewStyles" :src="src" @message="showMessage"></web-view>
</view>
</template>
<script>
export default {
data() {
return {
webviewStyles: {
progress: {
color: '#FF3333'
}
},
src:'http://******/', // H5项目地址
qrCodeWv: null
}
},
onReady() {
// #ifdef APP-PLUS
let currentWebview = this.$scope.$getAppWebview()
setTimeout(() => {
this.wv = currentWebview.children()[0]
this.qrCodeWv = currentWebview.children()[0]
this.wv.setStyle({scalable:true})
},1000)
// #endif
},
methods: {
showMessage(event) {
if(event.detail.data && event.detail.data.length >0){
let dataInfo = event.detail.data[0]
console.log(dataInfo)
let type = dataInfo.type
if(type==='scan') {
this.startScanCode()
}
}
},
startScanCode() {
const self = this 
uni.scanCode({
onlyFromCamera: false,
scanType: ['qrCode'],
success: function(res) {
setTimeout(() => {
const result = res.result.replace(/'/g,'"')
self.qrCodeWv.evalJS(`appScanCodeResult('${result}')`)
})
},
complete: function(args){
console.log(args)
}
})
}
}
}
</script>

二、H5 Vue项目引入js

1、在public新建js文件夹uni.webview.1.5.4.js文件,uni.webview.js 最新版地址

http://gitee.com/dcloud/uni-app/raw/dev/dist/uni.webview.1.5.4.js

2、index.html 引入 public/js 下文件

<script src="js/uni.webview.1.5.4.js"></script>

3、main.js 定义回调方法和对象

window.appScanCodeResult = function (val) {
window.appScanCodeResultString = val
window.dispatchEvent(new CustomEvent("scanCodeResult"))
}

4、Vue扫码页面代码

created() {
window.addEventListener("scanCodeResult", this.handleAppScanCode, false) 
},
onBeforeDestroy() {
window.removeEventListener("scanCodeResult", this.handleAppScanCode)
},
methods: {
handleAppScanCode() {
const result = window.appScanCodeResultString
console.log('扫码返回值---result',result)
},
// 点击扫码按钮
saoCode() {
uni.postMessage({
data: {
type: "scan"
}
})
}
}

相关文章

基于ElementUi再次封装基础组件文档


基于ant-design-vue再次封装基础组件文档


vue3+ts基于Element-plus再次封装基础组件文档

本站无任何商业行为
个人在线分享 » Vue H5项目,怎么引入uni.webview sdk,调用uni postMessage实现手机扫描功能
E-->