vue3类型uniapp调用signalr
目录
背景
安装
renderjs
2编写业务逻辑代码
3编写renderjs代码
背景
后端使用.net6开发,长链接选择了微软的signalr而非原生的websocket
前端uniapp下vue3类型开发的app,需要通过长链接获取后端推送的消息
安装
npm install @microsoft/signalr
虽然安装和前端一样,但是无法像前端一样使用
renderjs
uniapp提供renderjs来帮助完成操作DOM、运行web端js库等功能
https://uniapp.dcloud.net.cn/tutorial/renderjs.html#renderjsuni-app,uniCloud,serverlesshttps://uniapp.dcloud.net.cn/tutorial/renderjs.html#renderjs这里signalr作为web端的js库 就必须使用这种方法
官方使用的示例是以echarts库作为示例的,可以下载示例项目参考代码
1 选择一个tab页面承载renderjs代码
这里我们选择我的'mine'页面
并在页面上添加元素
<view id='token' v-show='false'>{{token}}</view>
因为renderjs代码是无法调用uniapp的api的,所以只能通过这种方式获取缓存中的token
2 编写业务逻辑代码
注意:不支持<script setup>
vue3的话 必须使用setup函数,并且将renderjs调用的函数return出去
<script>
export default {setup() {//提供给renderjs调用的函数const test = param => {//用来处理业务逻辑console.log('test',param}}return{test}}
}
</script>
3 编写renderjs代码
renderjs里面封装signalr相关的代码
这里需要新建一个<script>标签,即同一个页面有两个script标签!
<script lang="renderjs" module="signalr">const signalR = require("@microsoft/signalr");export default {data() {return {connection: null,connected: false,//当前signalr是否连接上token: ''//连接signalr 后台需要token身份验证}},mounted() {setInterval(() => {this.start()}, 10 * 1000)},methods: {start() {let token = document.getElementById('token').innerHTMLif (!token) {this.clear()return} else {if (token === this.token) {//token没变if (this.connection) {if (!this.connected) {// 还没连上 重新连this.connect()}} else {this.init(token)this.connect()}} else {//token变了 重新建立连接!this.token = tokenthis.clear()this.init(token)this.connect()}}},clear() {//清空signalrthis.disconnect()this.connection = null},async connect() {//连接signalrtry {await this.connection.start()this.connected = true} catch (err) {this.connected = false}},async disconnect() {if (this.connection) {await this.connection.stop()this.connected = false} else {this.connected = false}},init(token) {this.connection = new signalR.HubConnectionBuilder().withUrl(你的服务器signalrUrl, {accessTokenFactory: () => token}).configureLogging(signalR.LogLevel.Information).build();this.connection.onclose(async error => {this.connected = false})this.connection.on(你的signalr方法名称, res => {//!!重要!! 调用实际业务逻辑方法(之前定义的test方法)this.$ownerInstance.callMethod('test', res)})}}}</script>