nvue中使用webview相互传参
1.需要注意的是nvue和vue的传参方式有所区别,以下讲解下nvue传参方式,需要vue传参的可查看我的另一个博文https://www.cnblogs.com/lizhao123/p/12005868.html
第一步你需要建一个nvue的文件如下
//nvue 中的webview需要自行设置宽高否则无法展示
<template> <view> <web-view ref="webview" src="/hybrid/html/local.html" style="width: 500px;height: 600px;" @onPostMessage="getMessage"></web-view> </view> </template> <script> export default { data(){ return { } }, onLoad() { setTimeout(()=>{ this.handlePostMessage('测试传参') },200) }, methods: { handlePostMessage(res) { this.$refs.webview.evalJs(`handleMessage()`); }, getMessage(e) { uni.showModal({ content: JSON.stringify(e.detail), showCancel: false }) } } } </script>
第二步建个h5页面,我这里用官方的local.html,需要改动下,需要把方法挂载到window下即可触发
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>本地网页</title>
<style type="text/css">
.btn {
display: block;
margin: 20px auto;
padding: 5px;
background-color: #007aff;
border: 0;
color: #ffffff;
height: 40px;
width: 200px;
}
.btn-red {
background-color: #dd524d;
}
.btn-yellow {
background-color: #f0ad4e;
}
.desc {
padding: 10px;
color: #999999;
}
</style>
</head>
<body>
<p class="desc">web-view 组件加载本地 html 示例,仅在 App 环境下生效。点击下列按钮,跳转至其它页面。</p>
<div class="btn-list">
<button class="btn" type="button" data-action="navigateTo">navigateTo</button>
<button class="btn" type="button" data-action="redirectTo">redirectTo</button>
<button class="btn" type="button" data-action="navigateBack">navigateBack</button>
<button class="btn" type="button" data-action="reLaunch">reLaunch</button>
<button class="btn" type="button" data-action="switchTab">switchTab</button>
</div>
<p class="desc" id="lizhao">网页向应用发送消息。注意:小程序端应用会在此页面后退时接收到消息。</p>
<div class="btn-list">
<button class="btn btn-red" type="button" id="postMessage">postMessage</button>
</div>
<!-- uni 的 SDK -->
<script type="text/javascript" src="https://unpkg.com/@dcloudio/uni-webview-js@0.0.1/index.js"></script>
<script type="text/javascript">
window.handleMessage=function(data){
alert('传来的参数'+data)
}
document.addEventListener('UniAppJSBridgeReady', function() {
document.querySelector('.btn-list').addEventListener('click', function(evt) {
var target = evt.target;
if (target.tagName === 'BUTTON') {
var action = target.getAttribute('data-action');
switch (action) {
case 'switchTab':
uni.switchTab({
url: '/pages/tabBar/API/API'
});
break;
case 'reLaunch':
uni.reLaunch({
url: '/pages/tabBar/API/API'
});
break;
case 'navigateBack':
uni.navigateBack({
delta: 1
});
break;
default:
uni[action]({
url: '/pages/component/button/button'
});
break;
}
}
});
document.querySelector("#postMessage").addEventListener('click', function() {
uni.postMessage({
data: {
action: 'message888888'
}
});
})
});
</script>
</body>
</html>

浙公网安备 33010602011771号