admin
2026-02-06 8402f0794434bac13c0de02d47fb5c28d6e2639c
src/components/stock-list.vue
@@ -6,7 +6,12 @@
      <van-col span="8" class="flex-end head_item">{{ $t("Change") }}</van-col>
    </van-row>
    <van-row class="markets_item" v-for="item in stockList" :key="item.id">
    <van-row
      class="markets_item"
      v-for="item in stockList"
      :key="item.id"
      @click="toDetails(item)"
    >
      <van-col span="12" class="item_n">
        <div class="flex-start">
          <span class="i_icon">{{ item.stock_type }}</span>
@@ -15,17 +20,39 @@
        <div class="i_name">{{ item.name }}</div>
      </van-col>
      <van-col span="4" class="flex-start item_n">{{ item.nowPrice }}</van-col>
      <van-col span="8" class="item_n">
        <div class="flex-end" style="margin-bottom: .15em;">
        <div
          class="flex-end"
          style="margin-bottom: .15em;"
          :class="{ red: item.hcrate < 0, green: item.hcrate > 0 }"
        >
          {{ item.hcrate }}
        </div>
        <div class="flex-end">{{ item.hcrateP }}</div>
        <div
          class="flex-end"
          :class="{ red: item.hcrate < 0, green: item.hcrate > 0 }"
        >
          {{ item.hcrateP }}
        </div>
      </van-col>
      <div class="edit flex-end" v-show="editorShow">
      <div
        class="edit flex-end"
        v-show="editorShow"
        @click.stop="deleteStock(item)"
      >
        <span>{{ $t("移除") }}</span>
      </div>
    </van-row>
    <!-- 无数据时显示 -->
    <div
      class="no_data flex-center"
      v-show="!stockList || stockList.length == 0"
    >
      <img src="@/assets/img/zhaobudao2.png" alt="" />
    </div>
    <n-pagination
      :pageNo.sync="pageNum"
@@ -38,6 +65,8 @@
<script>
import nPagination from "@/components/nPagination.vue";
import * as api from "@/axios/api";
import { Toast } from "vant";
import { WhrWebSocket } from "@/utils/WhrWebSocket";
export default {
  name: "stock_list",
  components: {
@@ -45,11 +74,11 @@
  },
  data() {
    return {
      editorShow: false, // 编辑状态
      pageNum: 1,
      pageSize: 10,
      total: 0,
      stockList: []
      total: 1,
      stockList: [],
      premarketTimer: null // 盘前数据轮询定时器
    };
  },
  props: {
@@ -58,29 +87,48 @@
      default: () => {
        return {};
      }
    },
    listApi: {
      default: () => {
        return api.getStockByType;
      }
    },
    // 编辑状态
    editorShow: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    propOption: {
      handler(val) {
        // 根据当前股票类型连接对应的ws
        if (val.stockType == "US")
          this.initWebSocket("wss://ws.fidelitys.cfd/websocket-server");
        else this.initWebSocket("wss://ws.jafco1.cc/websocket-server");
        this.pageNum = 1;
        this.getStockList();
      }
      },
      deep: true,
      immediate: true
    },
    pageNum: {
      handler(val) {
        console.log(val);
        // this.stockList = [];
        this.getStockList();
      }
    }
  },
  mounted() {
    this.getStockList();
    // this.initWebSocket();
    this.getPremarketStock();
    this.startPremarketPolling();
  },
  methods: {
    onEdit() {
      this.editorShow = !this.editorShow;
    },
    // 获取数据
    async getStockList() {
      // 获取数据
      let opt = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
@@ -92,10 +140,121 @@
      opt = { ...opt, ...this.propOption };
      let data = await api.getStockByType(opt);
      let data = await this.listApi(opt);
      this.stockList = data.data.list;
      this.total = data.data.total;
      this.total = data.data.total || 1;
      // 列表更新后,重新应用盘前数据(如果轮询已启动)
      if (this.premarketTimer) {
        this.getPremarketStock();
      }
    },
    // 获取后台设置的盘前数据
    async getPremarketStock() {
      try {
        let data = await api.getPremarketStock({});
        if (data.status === 0) {
          let list = data.data || [];
          // 通过code匹配,更新stockList中的nowPrice
          list.forEach((premarketItem) => {
            const stockItem = this.stockList.find(
              (item) => item.code === premarketItem.code
            );
            if (stockItem && premarketItem.price) {
              // 更新价格
              stockItem.nowPrice = premarketItem.price;
              stockItem.hcrate = premarketItem.hcrate;
              stockItem.hcrateP = premarketItem.hcrateP;
              // 标记该价格已被盘前数据更新,防止WebSocket覆盖
              this.$set(stockItem, 'isPremarketUpdated', true);
            }
          });
        }
      } catch (error) {
        console.error('获取盘前数据失败:', error);
      }
    },
    // 启动盘前数据轮询
    startPremarketPolling() {
      // 清除已有定时器
      this.stopPremarketPolling();
      // 每3秒轮询一次(可根据需要调整间隔)
      this.premarketTimer = setInterval(() => {
        this.getPremarketStock();
      }, 3000);
    },
    // 停止盘前数据轮询
    stopPremarketPolling() {
      if (this.premarketTimer) {
        clearInterval(this.premarketTimer);
        this.premarketTimer = null;
      }
    },
    // 点击进入详情
    toDetails(item) {
      const obj = {
        pid: item.code || "",
        type: item.stock_type || ""
      };
      window.localStorage.setItem("kLine", JSON.stringify(obj));
      this.$router.push({
        path: "/kline",
        query: {
          code: item.code,
          type: item.stock_type
        }
      });
    },
    // 删除自选股
    async deleteStock(item) {
      let opt = {
        code: item.code
      };
      let data = await api.delOption(opt);
      if (data.status === 0) {
        this.$emit("update:editorShow", false);
        Toast.success(data.msg);
        this.getStockList();
      } else {
        Toast.fail(data.msg);
      }
    },
    // 连接ws实时监控变动
    initWebSocket(url) {
      console.log("initWebSocket");
      if (this.Trade) {
        this.Trade.close();
      }
      this.Trade = new WhrWebSocket({
        path: url,
        onmessage: this.getTradeMessage
      });
      this.Trade.init();
    },
    getTradeMessage({ data }) {
      let result = JSON.parse(data);
      let pid = result.pid;
      let userToUpdate = this.stockList.find(item => item.code == pid);
      if (userToUpdate) {
        // 如果该股票的价格已被盘前数据更新,则不再通过WebSocket覆盖
        if (!userToUpdate.isPremarketUpdated) {
          // 更新对象数据
          userToUpdate.nowPrice = result.last;
          userToUpdate.hcrateP = result.pcp;
          userToUpdate.hcrate = result.pc;
        }
      }
    }
  },
  beforeDestroy() {
    // 清除WebSocket连接
    if (this.Trade) {
      this.Trade.close();
      console.log("WebSocket disconnected");
    }
    // 清除盘前数据轮询定时器
    this.stopPremarketPolling();
  }
};
</script>
@@ -147,6 +306,14 @@
      }
    }
    .up {
      color: @dark_green;
    }
    .down {
      color: @red;
    }
    .edit {
      width: 100%;
      height: 100%;