VUE 集成websocket服务
1.示例截图
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' ,
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 ( )
this . websock. onclose = function ( e) {
console. log ( e)
}
}
}
}
< / script>
< style scoped>
< / style>