前端UniApp使用SignalR实例及踩的坑

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>

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值