Vue+WebSocket实现在线聊天
好了,话不多说,直接上代码!
<template>
<div class="hobnob-box">
<div class="txt-box">
<input ref="sendMssage" v-model="valueTxt" type="text" @keyup.enter="handleSend()" />
<button @click="handleSend()">发送消息</button>
</div>
</div>
</template>
<script>
export default {
data () {
return {
socket: null,
valueTxt: ''
}
},
mounted () {
// 初始化
this.initWebSocket()
},
destroyed () {
// 离开页面时关闭websocket连接
this.socket.onclose(undefined)
},
methods: {
/**
* 初始化进入页面创建websocket连接
*/
initWebSocket () {
let _this = this
// 判断页面是否已存在websocket连接
if (window.WebSocket) {
// 设置连接地址
var url = `http://192.168.0.132:40111/chart?userid=${this.userId}`
// 实例化WebSocket
let socket = new WebSocket(url)
_this.socket = socket
// 监听WebSocket连接
socket.onopen = (e) => {
this.$message.success('服务器连接成功')
}
// 监听WebSocket关闭消息
socket.onclose = (e) => {
this.$message.success('服务器连接关闭')
}
// 监听WebSocket错误消息
socket.onerror = () => {
this.$message.error('服务器连接出错l')
}
// 监听WebSocket返回消息
socket.onmessage = (e) => {
let resData = JSON.parse(e.data)
console.log(resData)
}
}
},
/**
* 发送聊天消息
*/
handleSend () {
let _this = this
// 输入框聚焦
_this.$refs['sendMssage'].focus()
if (!_this.valueTxt) {
return
}
// 调用WebSocket.send()发送消息的方法
_this.socket.send(_this.valueTxt)
_this.valueTxt = ''
// 设置消息滚动位置
setTimeout(() => {
let el = this.$refs['hobnob-box']
el.scrollTop = el.scrollHeight
}, 500)
}
}
}
</script>