在vue3中如何封装websocket
时间: 2024-01-21 20:45:37 浏览: 119
websoket.pdf
在 Vue3 中,可以通过自定义一个 WebSocket 的 Vue 插件来封装 WebSocket 功能,具体步骤如下:
1. 创建一个 vue-websocket.js 文件,代码如下:
```javascript
class WebSocketPlugin {
constructor(url) {
this.url = url;
this.websocket = null;
this.onMessageCallbacks = [];
}
connect() {
this.websocket = new WebSocket(this.url);
this.websocket.onopen = () => {
console.log('WebSocket opened');
};
this.websocket.onclose = () => {
console.log('WebSocket closed');
};
this.websocket.onmessage = (event) => {
this.onMessageCallbacks.forEach((callback) => {
callback(JSON.parse(event.data));
});
};
}
send(data) {
this.websocket.send(JSON.stringify(data));
}
onMessage(callback) {
this.onMessageCallbacks.push(callback);
}
}
export default {
install: (app, options) => {
const ws = new WebSocketPlugin(options.url);
app.config.globalProperties.$ws = ws;
app.provide('ws', ws);
ws.connect();
},
};
```
2. 在 main.js 中注册该插件,代码如下:
```javascript
import { createApp } from 'vue';
import App from './App.vue';
import WebSocketPlugin from './vue-websocket';
const app = createApp(App);
app.use(WebSocketPlugin, { url: 'ws://localhost:8080' });
app.mount('#app');
```
3. 在 Vue 组件中使用 WebSocket,代码如下:
```javascript
<template>
<div>
<button @click="send">Send</button>
</div>
</template>
<script>
export default {
mounted() {
this.$ws.onMessage((data) => {
console.log(data);
});
},
methods: {
send() {
this.$ws.send({ message: 'Hello WebSocket' });
},
},
};
</script>
```
以上是一个简单的 Vue3 中封装 WebSocket 的示例代码,可以根据自己的需求进行修改和扩展。
阅读全文