vue3中,使用typescript+pinia封装一个websocket.ts,支持断线重连,主动关闭则不自动重连,返回连接状态信息等,提供详细的代码
时间: 2024-10-15 07:17:30 浏览: 76
在 Vue 3 中使用 TypeScript 和 Pinia 构建一个 WebSocket 实例,我们需要首先安装必要的依赖,包括 `vue@next`, `ts-node` (用于运行 TypeScript 文件), `axios`(处理 HTTP 请求), `socket.io-client` (WebSocket 客户端库) 和 `pinia`。以下是一个基本的示例:
```bash
npm install -D typescript axios socket.io-client pinia ts-node
```
创建一个名为 `store/websocket.ts` 的文件,开始编写WebSocket服务:
```typescript
// websocket.store.ts
import { defineStore } from 'pinia';
import { createSocketIOInstance, SocketIOClientOptions } from 'socket.io-client';
interface ConnectionState {
connected: boolean;
reconnecting: boolean;
}
export type WebsocketAction = 'connect' | 'disconnect' | 'reconnect';
const defaultConnectionState: ConnectionState = {
connected: false,
reconnecting: false,
};
const useWebSocketStore = defineStore('websocket', {
state: () => ({
connectionState: defaultConnectionState,
}),
actions: {
async init(options: SocketIOClientOptions): Promise<void> {
const socket = createSocketIOInstance(options);
socket.on('connect', () => {
this.connectionState.connected = true;
this.connectionState.reconnecting = false;
// 在这里发送初始化消息或其他操作
console.log('Connected to the server');
});
socket.on('reconnect_error', () => {
this.connectionState.reconnecting = true;
});
socket.on('disconnect', () => {
this.connectionState.connected = false;
this.connectionState.reconnecting = false;
console.log('Disconnected from the server');
});
// 主动断开时调用此方法
this.closeConnection();
},
closeConnection() {
if (!this.connectionState.connected) return; // 如果已断开,则不执行
socket.disconnect();
},
attemptReconnect(): void {
if (!this.connectionState.reconnecting && !this.connectionState.connected) {
this.init({ reconnection: true }); // 设置自动重连选项
}
},
getConnectionStatus(): ConnectionState {
return this.connectionState;
},
},
});
export default useWebSocketStore;
```
然后在你的 Vue 组件或全局组件中注入并使用这个 store:
```typescript
// main.ts 或某个需要的地方
import { createApp } from 'vue';
import App from './App.vue';
import useWebSocket from '@/store/websocket';
createApp(App)
.use(Pinia)
.use(useWebSocket)
.mount('#app');
// 使用 store
export default {
setup() {
const wsStore = useWebSocket();
// 监听状态变化
wsStore.$watch(() => wsStore.connectionState, (newState) => {
console.log(`Current Connection State: ${JSON.stringify(newState)}`);
});
// 当需要时触发重连尝试
wsStore.attemptReconnect();
// 关闭连接时手动调用
onSomeCondition(wsStore.closeConnection);
return {};
},
};
```
阅读全文