您的位置:首页 > Web前端 > Vue.js

Vue中如何使用websocket

2019-07-03 16:26 295 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/qq_21692693/article/details/94571163

1新建文件夹 socket.js(目录自己看着办,可以放lib或者utils)

[code]import Vue from 'vue'
const ReconnectingWebSocket = require('@/api/webSocket/reconnecting-websocket.min.js') // https://github.com/joewalnes/reconnecting-websocket

/**
* @param {params.userId} string 用户id
*/
export default function initWebSocket (params) { // 初始化weosocket
let port = '8888' //测试:端口
let uri = '192.168.**.**' // 测试 地址
let url = `ws://${uri}:${port}/${params.userId}`

if ('WebSocket' in window) {
Vue.prototype.$socket = new ReconnectingWebSocket(url, null, {
debug: false, // console.debug()记录调试消息
automaticOpen: true, // 实例化后立即连接 ws.open()和 ws.close() 可以手动管理
reconnectInterval: 1000, // 重新连接延迟时间
maxReconnectInterval: 2000, // 等待重连最长时间
reconnectDecay: 1, // 延迟重连时间的增加率
timeoutInterval: 3000, // 在关闭和重试之前等待连接成功的最长时间
maxReconnectAttempts: null, // 最大尝试重连次数
binaryType: 'blob' // 二进制类型
})

Vue.prototype.$socket.sendObj = (data) => {
Vue.prototype.$socket.send(JSON.stringify(data))
}
} else {
alert('您的浏览器不支持 WebSocket!')
}
}

2 reconnecting-websocket.min.js下载地址 https://github.com/joewalnes/reconnecting-websocket

3如何去使用,首先上面的userId是用户登录之后返回的数据,用于建立websocket连接,login.vue中this.$cookie.set(userId:data.userId)而来的

目前我是在app.vue中去全局引用通过websocket.onmessage去监听并改变store中定义的数据,代码如下

[code]import socket from '@/api/socket'  //更具你自己的文件去引入之前新建的js

//钩子函数去初始化socket
created () {
let userId = this.$cookie.get('userId')//获取登陆后的userId
userId && socket({ userId: userId })
userId && this.bindSocketHandle() // 强制刷新浏览器后重新连接socket并绑定事件
},

bindSocketHandle方法如下

[code]  methods: {
bindSocketHandle () {
this.$socket.onmessage = this.getMessageInfo  //之前vue中原型已经注册所以可以直接使用
this.$socket.onclose = this.socketClose  //关闭后的方法我就不举例了
this.$socket.onerror = this.socketError   //错误时调用的方法我就不举例了
},
getMessageInfo({ data }){
let msg = JSON.parse(data)  //后端返回的是json数据,需要转换
switch (msg.uri) {
case '11':
this.$store.commit('socket/UPDATE_SYSPUSHMSG', msg.data)//也可以试试用vuestore的mapActions
break
case '222':
this.$store.commit('socket/UPDATE_COUNTUNREAD', msg.data)
break

}

},

}

 

store里面我就不举例子了,最后提醒只要监听store state的数据是否改变(mapState)来进行对应的操作,可以放在computed里面,watch你喜欢也行吧,你喜欢就好.

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: