-
Notifications
You must be signed in to change notification settings - Fork 1
/
useSocket.js
64 lines (55 loc) · 1.53 KB
/
useSocket.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import { ref, watchEffect, watch } from 'vue'
import useWebSocket, { SocketStatus } from './useWebSocket'
// 用户的store,用于检测登录
import { useAdminStore } from '@stores/adminStore'
export default function useSocket() {
const { status, message, error, connect, disconnect } = useWebSocket({
url: 'your webosckt url',
heartBeatData: 'your heart data'
})
const { isLogin } = storeToRefs(useAdminStore())
const chatMessage = ref(null)
const socketStatusText = ref('')
window.addEventListener('offline', function () {
console.log('网络连接已断开')
})
window.addEventListener('online', function () {
console.log('网络连接已恢复')
// 在网络连接恢复后执行的操作
retryConnect()
})
watch(
() => status.value,
newVal => {
if (newVal != SocketStatus.Connected) {
socketStatusText.value = newVal
}
}
)
watch(
() => message.value,
newVal => {
if (newVal) {
chatMessage.value = newVal
}
}
)
watchEffect(() => {
// 检测登录后就发起连接,退出后断开连接
if (isLogin.value) {
connect()
} else {
disconnect()
}
})
const retryConnect = () => {
if (status.value !== SocketStatus.Connected) {
connect()
}
}
return {
socketStatusText,
chatMessage,
retryConnect
}
}