webview与nvue/vue的通信及其遇到问题处理

1.web-view

<web-view @message='lisMessage' ref="webview" src="/hybrid/html/local.html"></web-view>

首先我们你需要知道在uni的项目中为什么需要用到webview。在vue/nvue中为什么需要用到web-view?

web-view 是一个 web 浏览器组件,可以用来承载网页的容器,会自动铺满整个页面(nvue 使用需要手动指定宽高)。

App端的webview是非常强大的,可以更灵活的控制和拥有更丰富的API。

每个vue页面,其实都是一个webview,而vue页面里的web-view组件,其实是webview里的一个子webview。这个子webview被append到父webview上。

web-view的介绍参考uni官方文档:https://uniapp.dcloud.io/component/web-view?id=web-view

说一个vue中设置webview不考虑全屏设置样式参考:

// #ifdef APP-PLUS
var currentWebview = this.$scope.$getAppWebview()
setTimeout(function() {
var wv = currentWebview.children()[0]
this.currentWebview = currentWebview.children()[0];
wv.setStyle({
// top:plus.screen.resolutionHeight - plus.navigator.getSafeAreaInsets().deviceTop - plus.navigator.getSafeAreaInsets().deviceBottom -330,
// top:200,
// top:plus.navigator.getSafeAreaInsets().deviceTop,
bottom:plus.navigator.getSafeAreaInsets().deviceBottom,
left:5,
right:100,
plus.screen.resolutionWidth-100,
// height:330,
background:'transparent',
})
}, 500); //如果是页面初始化调用时,需要延时一下

// #endif
// #ifndef MP-ALIPAY
this.videoCtx = uni.createVideoContext('myVideo')

// #endif

},

2.从vue/nvue传参或者调用html(webview)的方法/函数一般分为两种方式:

(1)通过web-view组件的url传参:

注意点:this.$refs.webview.evalJs("javascript:"+fn+"("+JSON.stringify(getApp().globalData.arguments.config)+")"); 

fn 是函数名 看你html定义的什么函数,这个fn原来是当字符串使用,括号内的参数看自己需要可传可不传。

例如:

<web-view @message='lisMessage' ref="webview" :src="'/hybrid/html/local.html?token='+token+'&uid='+uid+'&chatRoomId='+chatRoomId+'&nickname='+visNick "></web-view>
(2)通过evalJS(),调用webview的方法名,可将传入的参数带入。

例如: this.$mp.page.$getAppWebview().children()[0].evalJS("javascript:+xq_login"+"("+JSON.stringify(chatRoomObj)+")");

           this.$refs.webview.evalJs("javascript:+xq_login"+"("+JSON.stringify(chatRoomObj)+")");

 在遇到的小问题就是:  在nvue里使用可以调用webview里面的方法,但是在

当时在nvue中我使用的是  this.$refs.webview.evalJs("javascript:+xq_login"+"("+JSON.stringify(chatRoomObj)+")");  去调用webview的方法执行IM的登录。

但是在vue里执行却一直报错。打印出 this.$refs.webview也是会报错。就是underfined的吧。然而this.$scope.$getAppWebview()也是一样可以获取webview的。

后来发现

this.$mp.page.$getAppWebview().children()[0].evalJS('javascript:sendMsg()')     //使用这个调用方法就有效
// this.$scope.$getAppWebview.children()[0]         //使用这个调用方法就无效
其实需要注意的是:这个是用在 h5里的 下面使用在app里的。(可以通过 this.$scope 获取对应的app实例

3.webview向vue/nvue如何通信:

例如:

uni.postMessage({
data: {
msg:'网络不稳定'
}
});

在vue/nvue监听如下:

<web-view @message='lisMessage' ref="webview"  src="/hybrid/html/local.html"></web-view> 

收到监听处理业务逻辑:

lisMessage(event){
var data = event.detail.data[0].msg;
console.log(data,'消息打印啊');
// console.log(JSON.parse(data),'传过来的对象消息啊')
},

总结下个人感悟对于从vue/nvue传参或者调用html(webview)的方法/函数一般分为两种方式 根据自身业务逻辑和实际应用场景去具体选择!

原文地址:https://www.cnblogs.com/robot666/p/14990601.html