uni-app使用经验—vue页面和html页面如何互相调用接口并传参
说明
最近在项目上有个移动端(uni-app)的需求,就是要在移动端APP上的vue页面中通过web-view组件来调用html页面,并且要实现在html页面中可以点击一个元素来调用vue页面中uni的API(扫码接口),同时也可以在vue页面中也可以调用html页面中的js函数并进行传参。
使用环境
1. HBuilderX版本:2.8.11.20200907
2. V3编译器
html页面调用vue页面中uni的API
引用依赖的文件
在 web-view 加载的 HTML 中调用 uni 的 API,需要在 HTML 中引用必要的 JS-SDK
<script type="text/javascript" src="//js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.0.1.52.js"></script>
注意:这些 JS 文件是在 web-view 加载的那个 HTML 文件中引用的,而不是 uni-app 项目中的文件。
监听 web-view 的 message 事件
监听 web-view 组件的 message 事件,然后在事件回调的 event.detail.data 中接收传递过来的消息。
<template>
<view>
<web-view src="http://192.168.1.1:3000/test.html" @message="handleMessage"></web-view>
</view>
</template>
<script>
export default {
methods: {
handleMessage(evt) {
console.log('接收到的消息:' + JSON.stringify(evt.detail.data));
}
}
}
</script>
调用的时机
在引入上面的依赖文件后,需要在HTML中监听UniAppJSBridgeReady,事件触发后,
才能安全调用uni的API。
<script type="text/javascript" src="//js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.0.1.52.js"></script>
<script>
document.querySelector('.btn-list').addEventListener('click', function(evt) {
var target = evt.target;
if (target.tagName === 'BUTTON') {
var action = target.getAttribute('data-action');
if(action === 'navigateTo') {
uni.postMessage({
data: {
action: 'postMessage'
}
});
}
}
});
</script>
上面代码的意思就是在html页面中点击按钮列表中的某个按钮,
触发了uni.postMessage接口,进而调用了vue页面methods中的handleMessage方法,
并将参数data传给了vue页面。
在vue页面中调用html页面的js函数
示例代码:
var currentWebview = this.$mp.page.$getAppWebview().children()[0];
currentWebview.evalJS("htmljsfuc('"+res.result+"')");
其中的htmljsfuc就是要在html页面中定义的js函数。
完整代码示例:
<template>
<view>
<web-view :src="url" @message="handleMessage" ref="webview"></web-view>
</view>
</template>
<script>
export default {
data() {
return {
url:'http://192.168.81.102:8021/test.html',
webviewStyles: {
progress: {
color: '#FF3333'
}
}
};
},
methods: {
handleMessage(evt) {
console.log('接收到的消息:' + JSON.stringify(evt.detail.data));
var that=this;
uni.scanCode({
success: function (res) {
console.log('条码类型:' + res.scanType);
console.log('条码内容:' + res.result);
//将扫码结果传给html页面
var currentWebview = that.$mp.page.$getAppWebview().children()[0];
currentWebview.evalJS("htmljsfuc('"+res.result+"')");
uni.showModal({
content: '扫码成功!\n'+'扫码结果:' + res.result,
showCancel: false
});
}
});
}
}
}
</script>
<style></style>