1.因为可能是全局使用,所以,websocket就在app文件里去建立连接
import { mapGetters,mapActions } from 'vuex'
export default {
name: 'App',
computed: {
...mapGetters([
'token',
]),
},
data () {
return {
path:"ws://192.168.0.23:8002/frame/websocket.do",
socket:"",
timer:''
}
},
created () {
// 初始化
this.init()
},
methods: {
...mapActions(['websocket/saveMsg']),
init: function () {
if(typeof(WebSocket) === "undefined"){
alert("您的浏览器不支持socket")
}else{
this.connection();
let self = this;
// 断开重连机制,尝试发送消息,捕获异常发生时重连
this.timer = setInterval(() => { //10分钟检查一次是否连接
try {
self.socket.send();
} catch (err) {
console.log("断线了!!!" );
self.connection();
}
}, 600000);
}
},
connection(){
// 实例化socket,第一个参数是地址,第二个是参数,有则传,没有就不写
this.socket = new WebSocket(this.path,this.token)
// 监听socket连接
this.socket.onopen = this.open
// 监听socket错误信息
this.socket.onerror = this.error
// 监听socket消息
this.socket.onmessage = this.getMessage
// 监听socket断开信息
this.socket.onclose = this.close
},
open: function () {
console.log("socket连接成功")
},
error: function () {
console.log("连接错误")
},
getMessage: function (msg) {
let data=JSON.parse(msg.data);
console.log(data)
//todo 存到store,这里是我自己写的方法,'websocket/saveMsg'是方法名
this['websocket/saveMsg'](data.messageList)
},
close: function () {
console.log("socket已经关闭")
}
},
beforeDestroy: function () {
// 页面离开时断开连接,清除定时器
this.socket.onclose = this.close
clearInterval(this.timer);
},
}
2.其他组件使用
参考:https://www.cnblogs.com/qisi007/p/10213886.html
https://juejin.im/post/5b7fd02d6fb9a01a196f6276
网友评论