问题描述
在vue前端项目开发过程中需要实时显示部分数据,在通过多个处理方式中选择使用websocket来解决这个问题。
解决方案
vue单页代码
export default {
// 关闭页面时断开socket连接
beforeDestroy () {
this.websocketclose()
},
methods: {
// 初始化websocket
initWebsocket () {
// getUrl()访问服务器获取ip地址方法
getUrl().then(res => {
// 地址通过后端获取
this.path = res.data.data
this.websock = new WebSocket('ws://' + this.path + ':8080/websocket/' + getUser())
this.websock.onopen = this.websocketonopen
this.websock.onerror = this.websocketonerror
this.websock.onmessage = this.websocketonmessage
// this.websock.onclose = this.websocketclose
// 路由跳转时结束websocket链接
/* this.$router.afterEach(function () {
this.websock.close()
}) */
})
},
// 打开连接
websocketonopen () {
this.websocketsend('hello')
console.log('WebSocket连接成功')
},
// 连接错误
websocketonerror (e) {
console.log('WebSocket连接发生错误')
},
// 数据接收
websocketonmessage (e) {
console.log(e)
console.log('数据已接收...')
// console.log(redata.value)
},
// 数据发送
websocketsend (agentData) {
this.websock.send(agentData)
},
// 关闭连接
websocketclose () {
console.log('connection closed')
this.websock.close()
},
},
data () {
return {
path: '', // 保存ip地址
websock: '', // 保存socket连接对象
},
created () {
if (typeof (WebSocket) === 'undefined') {
alert('您的浏览器不支持socket')
} else {
this.initWebsocket() // 初始化websocket
}
}
}
}
现象
注意:具体业务实现根据自己的应用场景通过后端进行数据推送