9433cfb9创建于 2025年12月31日历史提交
<template>
  <scroll-view class="container">
    <view class="status-section">
      <text class="status-label">Worker状态: </text>
      <text class="status-text">{{statusText}}</text>
    </view>

    <view class="button-group">
      <text class="description-text">操作步骤:1.创建Worker 2.添加消息监听 3.发送数据测试</text>
      <button class="btn" type="primary" :disabled="created_boolean" @click="create">创建Worker</button>
      <button class="btn" type="primary" @click="onWorkerMsg">添加消息监听</button>
      <button class="btn" type="primary" @click="onWorkerError">添加错误监听</button>
      <button class="btn" @click="destory" :disabled="workerStatus != 'created'">销毁Worker</button>
    </view>

    <view class="input-section">
      <text class="section-title">输入测试值:</text>
      <text class="description-text">点击发送按钮后,会将输入值传给WorkerTask,在子线程执行+1操作后返回结果</text>
      <input class="input-field" v-model="inputValue" type="number" placeholder="请输入数字" />
      <button class="btn" type="primary" @click="sendMessage" :disabled="workerStatus != 'created'">发送到WorkerTask (值+1)</button>
    </view>

    <view class="log-section">
      <text class="section-title">通信日志:</text>
      <scroll-view class="log-container" scroll-y="true">
        <view v-for="(log, index) in logs" :key="index" class="log-item">
          <text :class="['log-text', log.type]">{{log.message}}</text>
        </view>
      </scroll-view>
      <button @click="clearLogs" class="btn clear-btn">清空日志</button>
    </view>

    <!-- #ifdef APP-HARMONY || WEB -->
    <view class="uni-btn-v">
      <navigator url="/pages/API/create-worker/worker-sendable-transfer">
        <button type="primary">worker sendable transfer 示例</button>
      </navigator>
    </view>
    <!-- #endif -->
  </scroll-view>
</template>

<script>
  export default {
    onUnload() {
      this.destory();
    },
    data() {
      return {
        created_boolean: false,
        workerStatus: 'none', // none, created, destroyed
        isListening: false,
        logs: [] as Array<UTSJSONObject>,
        inputValue: '1', // 默认值为1
        taskResult: '',
        worker: null as Worker | null
      }
    },
    computed: {
      statusText() : string {
        switch (this.workerStatus) {
          case 'none': return '未创建';
          case 'created': return '已创建';
          case 'destroyed': return '已销毁';
          default: return '未知';
        }
      }
    },
    methods: {
      // 添加日志方法
      addLog(message : string, type : string = 'info') {
        const now = new Date();
        const timeStr = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}:${now.getSeconds().toString().padStart(2, '0')}`;
        const logItem = {
          message: `[${timeStr}] ${message}`,
          type: type,
          time: timeStr
        } as UTSJSONObject;
        this.logs.unshift(logItem);
        // 限制日志数量
        if (this.logs.length > 50) {
          this.logs = this.logs.slice(0, 50);
        }
      },

      // 创建Worker
      create() {
        this.worker = uni.createWorker('workers/helloWorkerTask.uts');
        this.workerStatus = 'created';
        this.addLog('Worker创建成功', 'success');
        this.created_boolean = true;

      },
      onWorkerMsg() {
        if (this.worker == null) {
          this.addLog('请先创建worker', 'warning');
          return;
        }
        this.worker!.onMessage((result) => {
          // 处理Worker返回的消息
          console.log(`收到Worker消息:`, result);
          const res = result as UTSJSONObject;
          const resultData = res['data'] as string;
          this.taskResult = resultData;
          this.inputValue = this.taskResult
          this.addLog(`收到WorkerTask返回: ${resultData}`, 'receive');
        })
      },
      onWorkerError() {
        if (this.worker == null) {
          this.addLog('请先创建worker', 'warning');
          return;
        }
        this.worker!.onError((error) => {
          console.error('Worker发生错误:', error);
          // this.addLog(`Worker错误: ${error.message}`, 'error');
        })
      },

      // 向workerTask发送消息
      sendMessage() {
        // 检查输入值
        if (this.inputValue == '') {
          this.addLog('请输入有效的数字', 'warning');
          return;
        }
        const options = {
          data: this.inputValue,
          needReply: true
        };
        this.worker!.postMessage(options, null);
        this.addLog(`发送值到WorkerTask: ${this.inputValue}`, 'send');
      },

      // 销毁Worker
      destory() {
        if (this.worker == null) {
          this.addLog('没有创建worker,无法销毁', 'warning');
          return;
        }
        this.worker!.terminate();
        this.workerStatus = 'destroyed';
        this.isListening = false;
        this.addLog('Worker已销毁', 'warning');
        this.created_boolean = false;
      },

      // 清空日志
      clearLogs() {
        this.logs = [];
      },

      test_resetInputValue() {
        this.inputValue = '1'
      },
    }
  }
</script>

<style>
  .container {
    flex: 1;
    padding: 10px;
  }

  .status-section {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 20px;
    padding: 10px;
    background-color: #ffffff;
    border-radius: 8px;
  }

  .status-label {
    font-size: 16px;
    color: #666666;
  }

  .status-text {
    font-size: 16px;
    font-weight: bold;
    margin-left: 8px;
  }


  .button-group {
    flex-direction: column;
    margin-bottom: 10px;
  }

  .input-section {
    margin-bottom: 20px;
    padding: 15px;
    background-color: #ffffff;
    border-radius: 8px;
  }

  .input-field {
    /* #ifdef MP-WEIXIN */
    height: 3em;
    /* #endif */
    width: 100%;
    padding: 12px;
    border: 1px solid #dddddd;
    border-radius: 6px;
    font-size: 16px;
    margin: 10px 0;
    background-color: #ffffff;
  }

  .btn {
    /*  height: 50px; */
    margin-bottom: 10px;
    padding: 5px 10px;
    border-radius: 6px;
    font-size: 14px;
    text-align: center;
  }

  .log-section {
    background-color: #ffffff;
    border-radius: 8px;
    padding: 15px;
  }

  .section-title {
    font-size: 18px;
    font-weight: bold;
    color: #333333;
    margin-bottom: 10px;
  }

  .log-container {
    height: 300px;
    border: 1px solid #dddddd;
    border-radius: 4px;
    padding: 10px;
    margin: 10px 0;
    background-color: #fafafa;
  }

  .log-item {
    margin-bottom: 5px;
  }

  .log-text {
    font-size: 12px;
    line-height: 1.4;
  }

  .log-text.info {
    color: #2196F3;
  }

  .log-text.success {
    color: #4CAF50;
  }

  .log-text.warning {
    color: #ff9800;
  }

  .log-text.error {
    color: #f44336;
  }

  .log-text.send {
    color: #9C27B0;
  }

  .log-text.receive {
    color: #009688;
  }

  .clear-btn {
    background-color: #ff9800;
    font-size: 12px;
    padding: 8px 12px;
    color: #ffffff;
    border-radius: 4px;
    text-align: center;
  }

  .description-text {
    font-size: 14px;
    color: #666666;
    line-height: 1.4;
    margin-bottom: 10px;
  }
</style>