dcc
2024-06-07 d5381ec06ab5f549fade867c3a874de613bdd5d4
src/components/trade-deep-data/index.vue
@@ -1,236 +1,305 @@
<template>
    <div class="deep-data">
        <div class="flex justify-between text-grey font-24">
            <div>
                <div>{{ $t('价格') }}</div>
                <div class="mt-5">(USDT)</div>
            </div>
            <div class="text-right items-end justify-end">
                <div class="">{{ $t('数量') }}</div>
                <div class="mt-5">({{ symbol.toUpperCase() || '--' }})</div>
            </div>
        </div>
        <div v-if="showType == 0 || showType == 1" class="flex justify-between pt-6 pb-6 font-26"
            v-for="(item, index) in greenData" :key="index" @click="onPrice(item.price)" :style="{
                'background': `linear-gradient(to right,${theme == 'dark' ? '#111111' : 'transparent'} 0%` +
                    (item.amount / greenData[greenData.length - 1].amount) * 100 + '%,rgba(94,186,137,.1) ' +
                    (item.amount / greenData[greenData.length - 1].amount) * 100 + '%,rgba(94,186,137,.1) 100%)'
            }">
            <div class="text-green">{{ item.price || '--' }}</div>
            <div class="text-right textColor" v-if="symbol == 'shib'">{{ fixDate(item.amount, $i18n) || '--' }}</div>
            <div class="text-right textColor" v-else>{{ item.amount || '--' }}</div>
        </div>
        <div class="text-red pt-16 font-34 font-700 text-center">{{ approximately || '--' }}
        </div>
        <div class="approximately-text pb-10 font-20 text-center">≈{{ price || '--' }}</div>
        <div v-if="showType == 0 || showType == 2" class="flex justify-between pt-6 pb-6 font-26"
            v-for="(item, index) in redData" :key="item + index" @click="onPrice(item.price)" :style="{
                'background': `linear-gradient(to right,${theme == 'dark' ? '#111111' : 'transparent'} 0%` +
                    (item.amount / greenData[greenData.length - 1].amount) * 100 + '%,rgba(246,70,93,.1) ' +
                    (item.amount / greenData[greenData.length - 1].amount) * 100 + '%,rgba(246,70,93,.1) 100%)'
            }">
            <div class="text-red ">{{ item.price || '--' }}</div>
            <div class="text-right textColor" v-if="symbol == 'shib'">{{ fixDate(item.amount, $i18n) || '--' }}</div>
            <div class="text-right textColor" v-else>{{ item.amount || '--' }}</div>
        </div>
  <div class="deep-data">
    <div class="flex justify-between text-grey font-24">
      <div>
        <div>{{ $t("价格") }}</div>
        <div class="mt-5">(USDT)</div>
      </div>
      <div class="text-right items-end justify-end">
        <div class="">{{ $t("数量") }}</div>
        <div class="mt-5">({{ symbol | _symbolName }})</div>
      </div>
    </div>
    <div
      v-if="showType == 0 || showType == 1"
      class="flex justify-between pt-8 pb-8 font-26"
      v-for="(item, index) in greenData"
      :key="index"
      @click="onPrice(item.price)"
      :style="{
        background:
          `linear-gradient(to right,${
            theme == 'dark' ? '#111111' : 'transparent'
          } 0%` +
          (item.amount / greenData[greenData.length - 1].amount) * 100 +
          '%,rgba(94,186,137,.1) ' +
          (item.amount / greenData[greenData.length - 1].amount) * 100 +
          '%,rgba(94,186,137,.1) 100%)',
      }"
    >
      <div class="text-green">{{ item.price || "--" }}</div>
      <div class="text-right textColor" v-if="symbol == 'shib'">
        {{ fixDate(item.amount, $i18n) || "--" }}
      </div>
      <div class="text-right textColor" v-else>{{ item.amount || "--" }}</div>
    </div>
    <div class="pt-30 pb-30">
      <div class="text-red pt-16 font-34 font-700 text-center">
        {{ approximately || "--" }}
      </div>
      <div class="approximately-text pb-10 font-20 text-center">
        ≈{{ price || "--" }}
      </div>
    </div>
    <div
      v-if="showType == 0 || showType == 2"
      class="flex justify-between pt-8 pb-8 font-26"
      v-for="(item, index) in redData"
      :key="item + index"
      @click="onPrice(item.price)"
      :style="{
        background:
          `linear-gradient(to right,${
            theme == 'dark' ? '#111111' : 'transparent'
          } 0%` +
          (item.amount / greenData[greenData.length - 1].amount) * 100 +
          '%,rgba(246,70,93,.1) ' +
          (item.amount / greenData[greenData.length - 1].amount) * 100 +
          '%,rgba(246,70,93,.1) 100%)',
      }"
    >
      <div class="text-red">{{ item.price || "--" }}</div>
      <div class="text-right textColor" v-if="symbol == 'shib'">
        {{ fixDate(item.amount, $i18n) || "--" }}
      </div>
      <div class="text-right textColor" v-else>{{ item.amount || "--" }}</div>
    </div>
  </div>
</template>
<script>
import { WS_URL } from '@/config'
let DEEP_LENGTH = 6
import { WS_URL } from "@/config";
let DEEP_LENGTH = 6;
import { fixDate } from "@/utils/utis";
import { _getHomeList } from '@/API/home.api'
import { mapGetters } from 'vuex';
import { _getHomeList } from "@/API/home.api";
import { mapGetters } from "vuex";
export default {
    name: 'TradeDeepData',
    props: {
        symbol: {
            type: String,
        },
        price: {
            type: String
        },
        showType: {
            type: Number,
            default: 0
        },
        selectValue: {
            type: Number,
        }
  name: "TradeDeepData",
  props: {
    symbol: {
      type: String,
    },
    data() {
        const init = []
        for (let i = 0; i < DEEP_LENGTH; i++) {
            init.push({ amount: '', price: '' })
        }
        return {
            fixDate,
            greenData: init,
            redData: init,
            socket: null,
            approximately: ''
        }
    price: {
      type: String,
    },
    computed: {
        ...mapGetters({
            theme: 'home/theme'
        }),
    showType: {
      type: Number,
      default: 0,
    },
    mounted() {
        // this.startDeepSocket()
        if (this.showType == 1 || this.showType == 2) {
            DEEP_LENGTH = 12
        } else {
            DEEP_LENGTH = 6
        }
        this.getHomeList()
    selectValue: {
      type: Number,
    },
    watch: {
        symbol(val) {
            this.startDeepSocket()
            this.getHomeList()
        },
        showType(val) {
            if (val == 1 || val == 2) {
                DEEP_LENGTH = 12
            } else {
                DEEP_LENGTH = 6
            }
        },
    },
    methods: {
        getHomeList() {
            _getHomeList(this.symbol).then((res) => {
                let numberText = res[0].close
                let numberLength = (numberText.substring(numberText.indexOf('.') + 1, numberText.length)).length
                console.log(numberLength)
                let arry = []
                let str = '0.'
                for (let j = 0; j < numberLength - 1; j++) {
                    str = str + '0'
                    arry.push(str)
                }
                let newArry = []
                arry.map((item) => {
                    let obj = {
                        name: item + '1',
                        value: (item.substring(item.indexOf('.') + 1, item.length)).length + 1
                    }
                    newArry.push(obj)
                })
                if (numberLength <= 2) {
                    let obj = [
                        {
                            name: '0.1',
                            value: 1,
                        },
                        {
                            name: '1',
                            value: -1,
                        },
                        {
                            name: '10',
                            value: -2,
                        },
                        {
                            name: '100',
                            value: -3,
                        }
                    ]
                    newArry = newArry.concat(obj)
                }
                if (this.symbol == 'shib') {
                    newArry = newArry.slice(-4)
                }
                let dataObj = {
                    arry: newArry,
                    numberLength: numberLength
                }
                this.$emit('getList', dataObj)
            })
        },
        startDeepSocket() { // 开启socket链接
            this.closeSocket()
            console.log('start deep')
            this.socket = new WebSocket(`${WS_URL}/3/${this.symbol}`)
            this.socket.onmessage = (evt) => {
                const { data } = evt
                const { code, data: _data } = JSON.parse(data)
                if (code / 1 === 0) {
                    this.handleDeep(_data)
                }
            }
        },
        handleDeep(data) { // 格式化数据
            this.deepData = data
            if (this.selectValue >= 1) {
                this.deepData.asks.map((item) => {
                    item.price = parseFloat(item.price).toFixed(this.selectValue)
                })
                this.deepData.bids.map((item) => {
                    item.price = parseFloat(item.price).toFixed(this.selectValue)
                })
            } else {
                if (this.selectValue == -1) {
                    this.deepData.asks.map((item) => {
                        item.price = item.price.substring(0, item.price.indexOf('.'))
                    })
                    this.deepData.bids.map((item) => {
                        item.price = item.price.substring(0, item.price.indexOf('.'))
                    })
                }
                if (this.selectValue == -2) {
                    this.deepData.asks.map((item) => {
                        item.price = item.price.substring(0, item.price.indexOf('.') - 1) + '0'
                    })
                    this.deepData.bids.map((item) => {
                        item.price = item.price.substring(0, item.price.indexOf('.') - 1) + '0'
                    })
                }
                if (this.selectValue == -3) {
                    this.deepData.asks.map((item) => {
                        item.price = item.price.substring(0, item.price.indexOf('.') - 2) + '00'
                    })
                    this.deepData.bids.map((item) => {
                        item.price = item.price.substring(0, item.price.indexOf('.') - 2) + '00'
                    })
                }
                // this.selectValue
            }
            const { asks, bids } = data
            //获取小数位数
            this.redData = asks.sort((prev, next) => prev.price - next.price).slice(0, DEEP_LENGTH)
            this.greenData = bids.sort((prev, next) => prev.price - next.price).slice(0, DEEP_LENGTH)
            this.approximately = this.deepData.asks[1].price
        },
        onPrice(price) {
            this.$emit('price', price)
        },
        closeSocket() {
            this.socket && this.socket.close()
            this.socket = null
        },
    },
    activated() {
        this.startDeepSocket()
    },
    deactivated() {
        this.closeSocket()
    },
    beforeDestroy() { //
        this.socket && this.socket.close()
        this.socket = null
  },
  data() {
    const init = [];
    for (let i = 0; i < DEEP_LENGTH; i++) {
      init.push({ amount: "", price: "" });
    }
    return {
      fixDate,
      greenData: init,
      redData: init,
      socket: null,
      approximately: "",
    };
  },
  computed: {
    ...mapGetters({
      theme: "home/theme",
    }),
  },
  mounted() {
    // this.startDeepSocket()
    if (this.showType == 1 || this.showType == 2) {
      DEEP_LENGTH = 12;
    } else {
      DEEP_LENGTH = 6;
    }
    this.getHomeList();
  },
  watch: {
    symbol() {
      const init = [];
      for (let i = 0; i < DEEP_LENGTH; i++) {
        init.push({ amount: "", price: "" });
      }
      this.greenData = init;
      this.redData = init;
      this.startDeepSocket();
      this.getHomeList();
    },
    showType(val) {
      if (val == 1 || val == 2) {
        DEEP_LENGTH = 12;
      } else {
        DEEP_LENGTH = 6;
      }
    },
  },
  methods: {
    getHomeList() {
      _getHomeList(this.symbol).then((res) => {
        let numberText = res[0].close;
        let numberLength = numberText.substring(
          numberText.indexOf(".") + 1,
          numberText.length
        ).length;
        console.log(numberLength);
        let arry = [];
        let str = "0.";
        for (let j = 0; j < numberLength - 1; j++) {
          str = str + "0";
          arry.push(str);
        }
        let newArry = [];
        arry.map((item) => {
          let obj = {
            name: item + "1",
            value:
              item.substring(item.indexOf(".") + 1, item.length).length + 1,
          };
          newArry.push(obj);
        });
        if (numberLength <= 2) {
          let obj = [
            {
              name: "0.1",
              value: 1,
            },
            {
              name: "1",
              value: -1,
            },
            {
              name: "10",
              value: -2,
            },
            {
              name: "100",
              value: -3,
            },
          ];
          newArry = newArry.concat(obj);
        }
        if (this.symbol == "shib") {
          newArry = newArry.slice(-4);
        }
        let dataObj = {
          arry: newArry,
          numberLength: numberLength,
        };
        this.$emit("getList", dataObj);
      });
    },
}
    startDeepSocket() {
      // 开启socket链接
      this.closeSocket();
      this.socket = new WebSocket(`${WS_URL}/3/${this.symbol}`);
      this.socket.onopen = () => {
        console.log("WebSocket connection established");
      };
      this.socket.onmessage = (evt) => {
        const { data } = evt;
        const { code, data: _data } = JSON.parse(data);
        if (code / 1 === 0) {
          this.handleDeep(_data);
        }
      };
      this.socket.onerror = (error) => {
        console.error("WebSocket error:", error);
        setTimeout(this.startDeepSocket, 5000); // 5秒后尝试重新连接
      };
      this.socket.onclose = (event) => {
        console.log("WebSocket connection closed:", event);
        // 重新连接,可以根据需求添加重连的逻辑,这里只是简单的示例
      };
    },
    handleDeep(data) {
      // 格式化数据
      // console.log(this.symbol, data.symbol);
      if (this.symbol !== data.symbol) {
        return;
      }
      this.deepData = data;
      if (this.selectValue >= 1) {
        this.deepData.asks.map((item) => {
          item.price = parseFloat(item.price).toFixed(this.selectValue);
        });
        this.deepData.bids.map((item) => {
          item.price = parseFloat(item.price).toFixed(this.selectValue);
        });
      } else {
        if (this.selectValue == -1) {
          this.deepData.asks.map((item) => {
            item.price = item.price.substring(0, item.price.indexOf("."));
          });
          this.deepData.bids.map((item) => {
            item.price = item.price.substring(0, item.price.indexOf("."));
          });
        }
        if (this.selectValue == -2) {
          this.deepData.asks.map((item) => {
            item.price =
              item.price.substring(0, item.price.indexOf(".") - 1) + "0";
          });
          this.deepData.bids.map((item) => {
            item.price =
              item.price.substring(0, item.price.indexOf(".") - 1) + "0";
          });
        }
        if (this.selectValue == -3) {
          this.deepData.asks.map((item) => {
            item.price =
              item.price.substring(0, item.price.indexOf(".") - 2) + "00";
          });
          this.deepData.bids.map((item) => {
            item.price =
              item.price.substring(0, item.price.indexOf(".") - 2) + "00";
          });
        }
        // this.selectValue
      }
      const { asks, bids } = data;
      //获取小数位数
      this.redData = asks
        .sort((prev, next) => prev.price - next.price)
        .slice(0, DEEP_LENGTH);
      this.greenData = bids
        .sort((prev, next) => prev.price - next.price)
        .slice(0, DEEP_LENGTH);
      this.approximately = this.deepData.asks[1].price;
    },
    onPrice(price) {
      this.$emit("price", price);
    },
    closeSocket() {
      this.socket && this.socket.close();
      this.socket = null;
    },
  },
  activated() {
    this.startDeepSocket();
  },
  deactivated() {
    this.closeSocket();
  },
  beforeDestroy() {
    //
    this.socket && this.socket.close();
    this.socket = null;
  },
};
</script>
<style  lang="scss" scoped>
.approximately-text {
    @include themify() {
        color: themed("text_color1");
    }
  @include themify() {
    color: themed("text_color1");
  }
}
</style>