UniApp H5+App前端使用SignalR时,H5端正常,App端异常,经查询和测试,总结如几点:
1、前端关于SignalR的代码要写成 renderjs,不然App端会报错“ReferenceError: require is not defined”
2、与SignalR相关的代码不能使用UniApp或其它第三方的的方法或组件,比如调用renderjs中的方法时,不能用<u-buttton>的click事件,否则H5正常,App没反应
3、在renderjs里通过this.$ownerInstance.callMethod()调用service层(正常<script> )里的方法
4、renderjs里如果想调用service层的变量,需要在<template>中使用" :change"监测然后传入renderjs
其它方面网上讲很多,自己查吧
<template>
<view style="margin-top: 200px;" class="renderjs">
<!-- <u-button @click="socket.sendMsg" text="Send"></u-button> -->
<!-- <u-button>不能用,在h5正常,app中无效,这个坑踩了好几天,希望能帮到你 -->
<button @click="socket.sendMsg">Send</button>
<u-button></u-button>
<!-- 通过监测host的改变,把host的值传入renderjs里 -->
<view :url="host" :change:url="socket.getHost"></view>
</view>
</template>
<script>
export default {
data() {
return {
//后端地址,通过 :change 可传入renderjs, 需要改成你自己实际的地址
host: "http://192.168.1.8:5278"
}
},
methods: {
reciveMsg(obj) {
//收到信息后进一步处理,由renderjs中的
//this.$ownerInstance.callMethod调用,obj为收到的内容
console.log("reciveMsg:", obj);
}
},
}
</script>
<script module="socket" lang="renderjs">
import * as signalR from "@microsoft/signalr"
var connection
export default {
data() {
return {}
},
methods: {
sendMsg(e, ownerVm) {
//console.log('ownerVm: ', ownerVm);
//调用后端的"SendMessage"方法
connection.invoke("SendMessage", "发送的数据")
},
getHost(newValue, oldValue, ownerVm, vm) {
//从service层动态获取后端地址
this.url = newValue
}
},
async mounted() {
//url 后端SignalR的地址
this.url = this.url + '/Hubs/Notifier'
connection = new signalR.HubConnectionBuilder()
.withUrl(this.url)
.configureLogging(signalR.LogLevel.Information)
.withAutomaticReconnect()
.build()
//监听 ReceiveMessage 事件,名称为invoke调用后端方法后,后端返回的事件名
await connection.on("ReceiveMessage", msg => {
//调用<script> 也叫service层的 reciveMsg 方法 msg为方法的参数
this.$ownerInstance.callMethod("reciveMsg", msg)
})
await connection.start()
},
}
</script>
<style>
</style>