引用不行就直接下载文件
<script src="[cdnjs.cloudflare.com/ajax/libs/socket.io/4.4.1/socket.io.js](https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.4.1/socket.io.js)
"></script>
<body>
<div class="container" id="app" v-cloak>
<h1 class="title">Web<span style="font-weight: 700">socket</span></h1>
<div class="message-wrap" ref="myWrap">
{{nickName}}
<div class="message" :class="{'self':item.isSelf}" v-for="(item,index) in messages " :key="index">
<div class="label">{{item.nickName}}</div>
<div class="value">
{{item.text}}
</div>
</div>
</div>
<div class="footer">
<input class="input" type="text" v-model="value" @keyup.enter="onSend" ref="myInput" />
<button class="button" @click="onSend">Send</button>
</div>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script src="./socket.io.js"></script>
<script>
const app = Vue.createApp({
data() {
return {
messages: [],
socket: null,
value: '',
nickName: ''
}
},
methods: {
handlerScrollBottom() {
this.$nextTick(() => {
this.$refs.myWrap.scrollTop = this.$refs.myWrap.scrollHeight;
console.log(this.$refs.myWrap.scrollTop, this.$refs.myWrap.scrollHeight);
})
},
onSend() {
if (!this.value) return;
// 发送消息
this.socket.emit("message", this.value);
this.messages.push({
nickName: this.nickName,
text: this.value,
isSelf: true
})
this.value = '';
this.$refs.myInput.focus();
// 滚动条置底部
this.handlerScrollBottom()
}
},
mounted() {
// 建立链接
this.socket = io("http://127.0.0.1:3000")
// socket = io("http://10.36.133.107:3000")
const name = window.prompt("请输入你的昵称")
if (!name) return;
// init事件
this.nickName = name;
this.socket.emit("init", this.nickName);
// 监听服务端发送的信息---别人发了信息
this.socket.on("message", (data) => {
this.messages.push(data);
// 滚动条置底部
this.handlerScrollBottom();
// console.log("message", data);
})
}
})
app.mount("#app")
</script>
</body>
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。