演示代码请根据实际需要进行修改
注:需要在同一域名下
H5的PHP代码
<script type="text/javascript" src="<?=cdn_url()?>/lib/uni.webview.1.5.5.js"></script>
<?php
$vue->created(['load_vue()']);
$vue->data('uni',"");
$vue->method("load_vue()","
document.addEventListener('UniAppJSBridgeReady', function() {
_this.uni = uni;
});
");
$vue->method("test()","
_this.uni.postMessage({
data:{
action:'login',
data:res.data,
}
});
");
?>
data结构
data:{data:{user_id:'',token:''}}
UNIAPP
<template>
<view>
<web-view :src="url" ref="view" @message="message"></web-view>
</view>
</template>
<script>
var _this
export default {
data() {
return {
url: ''
}
},
onLoad() {
_this = this
this.url = this.config.domain + '/applet/login'
// #ifdef H5
window.addEventListener("message", receive_message, false);
function receive_message(event) {
let res = event.data.data.arg
let action = res.action
let d = res.data
_this.login_listen(action, d)
}
// #endif
},
methods: {
message(e) {
console.log('on message')
console.log(e)
let res = e.detail.data[0]
let d = res.data
let action = res.action
_this.login_listen(action, d)
},
login_listen(action, d) {
if (action == 'login') {
if (d.token) {
uni.navigateBack()
}
}
}
}
}
</script>