VUE 集成websocket服务
2.socketDemo.vue页面代码
<!-- socket demo -->
<template>
<div class = "app-container">
<div class = "filter-container">
接收:
<el-input v-model = "news" type = "textarea" :rows = "4" class = "filter-item" placeholder = "没有消息"/>
</div>
<div class = "filter-container">
<el-input v-model = "messageWin" controls-position = "right" size = "small" @change = "initDisabledVal"/>
<el-button class = "filter-item" :disabled = "initDisabled" type = "primary" @click = "initWebSocket"> 初始化监控 {
{
initVal
}}
</el-button>
发送:
<el-input v-model = "messageVal" type = "textarea" :rows = "4" class = "filter-item"/>
<el-button class = "filter-item" type = "primary" @click = "pushMessage">发送</el-button>
</div>
<div>
<div ref = "print">数据实时监控页面</div>
</div>
</div>
</template>
<script>
import {
socketApi} from ../../../api/cm/cmApi
export default {
name: socket,
created() {
this.socketIp = window.global_config.CM_URL.substring(window.global_config.CM_URL.indexOf(://) + 3)
},
data() {
return {
initDisabled: false,
initVal: ,
socketIp: ,
websock: ,
news: ,
messageWin: 0001,//接入的ID
messageVal:
}
},
methods: {
initWebSocket() {
if (typeof (WebSocket) === undefined) {
console.log(您的浏览器不支持会话)
} else {
this.close()
this.initDisabled = true
this.websock = new WebSocket(ws:// + this.socketIp + /api/webLiveData/ + this.messageWin)
// 打开事件
this.websock.onopen = this.onopen
// 获得消息事件
this.websock.onmessage = this.onmessage
// 关闭事件
this.websock.onclose = this.onclose
// 发生了错误事件
this.websock.onerror = this.onerror
}
},
onopen() {
console.log(Socket 已打开)
},
onmessage(msg) {
// 接收到的消息进入
var data = JSON.parse(msg.data)
this.news = data.message
},
onclose() {
console.log(Socket已关闭)
},
onerror() {
this.$notify.error({
title: 发生了错误,
message: 此时可以尝试刷新页面,
type: error,
showClose: false
})
// 此时可以尝试刷新页面
},
pushMessage() {
socketApi.pushMessage(this.messageWin, {
message: this.messageVal}).then(res => {
console.log(发送消息结果:, res)
})
},
initDisabledVal() {
this.initDisabled = false
this.close()
},
close() {
if (this.websock == ) {
return
}
this.websock.close()// 关闭websocket
this.websock.onclose = function (e) {
console.log(e)// 监听关闭事件
}
}
}
}
</script>
<style scoped>
</style>