基于vue3写的简易版的即使通信
<template>
<div class="all">
<div class="all-page">
<div class="head">
<div>ws://192.168.50.112:8089/myWS</div>
<div>{{ showText }}</div>
</div>
<div class="main">
<div class="main-left"></div>
<div class="main-right">
<div class="main-right-a">
<div class="main-right-a-msg" v-for="item in msgList">
<span style="color: #00b969;margin-left: 20px">{{ item.user }}</span><span
style="margin: 0 20px">{{ item.msg }}</span><span style="color: #0f88eb">{{ item.time }}</span>
</div>
</div>
<div class="main-right-b">
<div id="inputContent" placeholder="请在这输入内容" :contenteditable="contenteditable"></div>
<div class="main-right-c">
<el-button type="primary" @click="send" style="margin-right: 10px">发送</el-button>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script setup>
import {onMounted, ref} from "vue";
import {formatDate} from "@/utils";
const msgList = ref([])
const socket = ref(null)
const showText = ref('连接中...')
const contenteditable = ref(false)
onMounted(() => {
//创建webSocket服务连接
socket.value = new WebSocket("ws://192.168.50.112:8089/myWS");
//连接成功
socket.value.onopen = function () {
showText.value = '已连接'
contenteditable.value = true
}
//收到服务端发来的消息
socket.value.onmessage = function (msg) {
msgList.value.push({
user: '服务端',
msg: msg.data,
time: formatDate(new Date())
})
}
//关闭连接
socket.value.onclose = function () {
showText.value = '已关闭'
};
//连接时发生异常
socket.value.onerror = function () {
showText.value = 'websocket发生了错误'
}
})
const send = () => {
const doc = document.getElementById('inputContent')
socket.value && socket.value.send(doc.innerText)
msgList.value.push({
user: '我',
msg: doc.innerText,
time: formatDate(new Date())
})
doc.innerText = ''
}
</script>
<style scoped>
.all {
width: 100%;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
.all-page {
width: 1200px;
height: 800px;
box-shadow: 0 10px 10px rgba(0, 0, 0, .2);
}
.head {
width: 100%;
height: 40px;
background-color: #0f88eb;
display: flex;
justify-content: space-between;
align-items: center;
color: white;
}
.head div {
padding: 0 15px;
}
.main {
width: 100%;
height: 760px;
background-color: #fafafa;
display: flex;
justify-content: space-between;
align-items: center;
}
.main-left {
width: 25%;
height: 100%;
}
.main-right {
width: 75%;
height: 100%;
border-left: 1px solid #c9c9c9;
}
.main-right-a {
width: 100%;
height: 600px;
overflow-y: scroll;
overflow-x: hidden;
}
.main-right-b {
width: 100%;
height: 160px;
background-color: white;
}
#inputContent {
width: 97%;
height: 100px;
padding: 10px;
}
#inputContent[contenteditable]:focus {
content: none;
outline: none;
}
#inputContent[contenteditable]:empty:before {
content: attr(placeholder);
color: #cccccc;
}
.main-right-c {
width: 100%;
height: 40px;
display: flex;
justify-content: flex-end;
align-items: center;
}
.main-right-a-msg {
width: 100%;
margin-top: 10px;
}
</style>