欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 家装 > vue项目中使用websocket

vue项目中使用websocket

2025/2/24 1:04:45 来源:https://blog.csdn.net/Dalin0929/article/details/142910778  浏览:    关键词:vue项目中使用websocket

一、单文件中引入使用

<template></template>
<script>export default {websocket: true, // 标志需要使用WebSocketdata () {return {ws: null}},created () {this.ws = new WebSocket('ws://127.0.0.1:8000'); // ws服务地址this.ws.onopen = () => {// 接收服务端消息this.ws.onmessage = res => {console.log(res.data);// 注:res.data是字符串类型,有需要可通JSON.parse进行转换}// 发送消息到服务端this.ws.send('测试数据');// 注:发送的数据需要是字符串类型,有需要可通过JSON.stringify转换}},beforeDestroy () {if (this.ws) {this.ws.close(); // 断开服务连接this.ws = null;}}}
</script>

二、全局引入使用

1、封装websocket.js

const WebSocketPlugin = {install(Vue) {let ws = null;Vue.prototype.$websocket = {init (url) {ws = new WebSocket(url);},send(message) {if (ws && ws.readyState === WebSocket.OPEN) {ws.send(message);}},onMessage(callback) {ws && (ws.onmessage = callback);},onOpen(callback) {ws && (ws.onopen = callback);},onClose() {ws && ws.close();},onError(callback) {ws && (ws.onerror = callback);}}}
}
export default WebSocketPlugin;

main.js全局引入

import Vue from "vue";
import WebSocketPlugin from './websocket.js';
Vue.use(WebSocketPlugin);

2、页面使用

<template>
</template>
<script>export default {websocket: true, // 标志需要使用WebSocketcreated () {this.$websocket.init('ws://127.0.0.1:8000');this.$websocket.onOpen(() => {// 接收服务端消息this.$websocket.onMessage(res => {console.log(res.data);})// 发送消息到服务端this.$websocket.send('测试数据');})},beforeDestroy () {this.$websocket.onClose();}}
</script>

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词