import { createStore } from 'vuex'
export default createStore({
state: {
messages: []
},
mutations: {
setMessages(state, payload) {
// 我们这里假设payload的格式为 { index: n, message: msg }
state.messages[payload.index] = payload.message
},
},
actions: {
}
})
修改WebSocketConnection 类,使其接收到消息的时候调用 setMessages mutation:
import { ref, onMounted, onUnmounted } from 'vue';
import store from '@/store'
class WebSocketConnection {
constructor(url, index) {
this.url = url;
this.index = index;
this.ws = new WebSocket(url);
this.bindEvents();
this.startSending();
}
bindEvents() {
// ...其它代码略 看上面
this.ws.onmessage = (message) => {
// 当接收到数据时,将数据保存到 Vuex
store.commit('setMessages', { index: this.index, message: message.data });
};
}
// ...其它代码略 看上面
}
// 在 onMounted 钩子函数中创建WebSocket连接
onMounted(() => {
const urls = ['wss://url1', 'wss://url2', 'wss://url3', 'wss://url4', 'wss://url5', 'wss://url6', 'wss://url7', 'wss://url8', 'wss://url9', 'wss://url10'];
wsConnections.value = urls.map((url, index) => new WebSocketConnection(url, index));
});
然后,在其他组件中以这种方式使用第一个Websocket的消息:
Received Message: {{ message }}
import { defineStore } from "pinia"
export const useUsersStore = defineStore('users', {
// 其它配置项
state: () => {
return {
messages: [],
};
},
getters: {
},
actions: {
setMessage(payload) {
this.messages[payload.index] = payload.messages
}
}
})
然后,在 WebSocketConnection 类中调用 setMessage 来储存数据:
import { ref, onMounted, onUnmounted } from 'vue';
import { useUsersStore } from "@/store/user.js";
class WebSocketConnection {
constructor(url, index) {
this.url = url;
this.index = index;
this.ws = new WebSocket(url);
this.store = useUsersStore();
this.bindEvents();
this.startSending();
}
bindEvents() {
// ...同上面
this.ws.onmessage = (message) => {
// 收到信息后,将其存储在Pinia中
this.store.setMessage({ index: this.index, message: message.data });
};
}
// ...同上面e...
}
onMounted(() => {
const urls = ['ws://url1', 'ws://url2', 'ws://url3', 'ws://url4', 'ws://url5',
'ws://url6', 'ws://url7', 'ws://url8', 'ws://url9', 'ws://url10'];
wsConnections.value = urls.map((url, index) => new WebSocketConnection(url, index));
});
onUnmounted(() => {
wsConnections.value.forEach(connection => {
connection.stopSending();
connection.ws.close();
});
});
然后在其他组件中可以像这样使用第一个连接收到的数据:
Received Message: {{ message }}