riku
2025-05-13 6c75516f1ba668873807cef33aa996d25cdf16c4
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<template>
  <BaseCard>
    <template #content>
      <div>
        <el-input type="text" v-model="inputVal" />
        <button @click="handleSend">send</button>
        <button @click="handleLink">link</button>
      </div>
      <div>业务状态中控</div>
      <el-scrollbar ref="scrollbarRef" :height="height">
        <div ref="scrollContentRef">
          <div v-for="(item, index) in streams" :key="index">
            <el-text type="primary">[{{ item }}]: </el-text>
          </div>
        </div>
      </el-scrollbar>
    </template>
  </BaseCard>
</template>
<script setup>
import { reactive, ref, onMounted, onUnmounted, inject } from 'vue';
import { ws } from '@/api/index';
 
const height = `60vh`;
 
const scrollContentRef = ref();
const scrollbarRef = ref();
 
function scrollToBottom() {
  const h1 = scrollContentRef.value.clientHeight + 100;
  setTimeout(() => {
    scrollbarRef.value.setScrollTop(h1);
  }, 100);
}
 
const streams = reactive([]);
 
let socket;
 
const inputVal = ref('');
const handleSend = () => {
  if (socket) {
    socket.send(inputVal.value);
  }
};
 
const handleLink = () => {
  if (socket) {
    socket.close();
  }
  const url = 'ws://' + ws + '/ws';
  // socket = new WebSocket(`ws://192.168.0.138:8080/workstream`)
  socket = new WebSocket(url);
  // 与服务器建立连接:发送消息到服务器
  socket.onopen = () => {
    console.log('connect: ');
  };
  // 收到服务器发送的消息:event处理服务器返回的数据
  socket.onmessage = (event) => {
    console.log('receive: ', event.data);
    putWorkStream(event.data);
  };
  // 连接或通信过程中发生错误
  socket.onerror = (event) => {
    console.log('errror: ', event);
  };
  // 与服务器断开连接
  socket.onclose = (event) => {
    console.log('close: ', event.code);
  };
};
 
/**
 * 添加一条工作流信息
 * @param {*} data
 */
function putWorkStream(data) {
  const obj = JSON.parse(data);
  streams.push(obj);
  scrollToBottom();
}
</script>