import { defineStore } from 'pinia'; import { ref } from 'vue'; import { getToken } from '@/common/common.js' import { get_base_url } from '@/api/request.js' import SocketClass from '@/api/socket.js' export const useSocketStore = defineStore('socketStore',{ state:()=>({ SocketObj: null }), getters:{ taskSocket(state){ return state.SocketObj } }, actions:{ creatSocket(url = '/trastudy/trasoket/open?summary='){ console.log('打开websocket'); if(this.SocketObj && this.SocketObj?.close && !this.SocketObj?.isClose) { return } if(this.SocketObj?.isClose){ this.SocketObj.isClose = false } let _baseUrl = get_base_url(url).split('http').join('ws') this.SocketObj = new SocketClass(_baseUrl + url + getToken()); }, closeSocket() { console.log('关闭websocket'); if(!(this.SocketObj && this.SocketObj?.close)) return this.SocketObj && this.SocketObj.close() }, setOnmessageCb(cb){ if(!this.SocketObj || !this.SocketObj?.on) return this.SocketObj.on('message', cb) } } }) // () => { // const SocketObj = ref() // const creatSocket = () => { // console.log(data) // if(SocketObj.value && SocketObj.value?.close) { // closeSocket() // } // SocketObj.value = new SocketClass(get_base_url() + '/trastudy/trasoket/open?summary=' + getToken()); // } // const closeSocket = () => { // if(!SocketObj.value || !SocketObj.value?.close) return // SocketObj.value && SocketObj.value?.close?.() // } // const setOnmessageCb = (cb) => { // if(!SocketObj.value || !SocketObj.value?.on) return // SocketObj.value.on('message', cb) // } // return { SocketObj, creatSocket, closeSocket, setOnmessageCb } // }