j1ack 3 years ago
parent
commit
83e966a566
  1. 8
      main.js
  2. BIN
      pages/markets/.DS_Store
  3. 94
      pages/markets/index.vue
  4. 288
      pages/markets/kLine.vue
  5. 156
      pages/markets/trade.vue
  6. 13
      utils/axios.js
  7. 184
      utils/websocket.js

8
main.js

@ -12,7 +12,11 @@ import ZH from './utils/language/zh_TW.js'
import VI from './utils/language/vi_VN.js' import VI from './utils/language/vi_VN.js'
import api from './utils/api.js' import api from './utils/api.js'
import constant from './utils/constant.js'
import websocket from './utils/websocket.js'
Vue.prototype.$api = api Vue.prototype.$api = api
Vue.prototype.$constant = constant
Vue.prototype.$websocket = websocket
// 自定义底部导航栏 // 自定义底部导航栏
import tabBar from 'components/tabBar/tabBar.vue' import tabBar from 'components/tabBar/tabBar.vue'
Vue.component('tab-bar', tabBar) Vue.component('tab-bar', tabBar)
@ -21,7 +25,9 @@ Vue.use(uView);
uni.$u.config.unit = 'rpx' uni.$u.config.unit = 'rpx'
Vue.use(VueI18n); Vue.use(VueI18n);
// #ifdef H5
window.wx = {}
// #endif
const i18n = new VueI18n({ const i18n = new VueI18n({
locale: store.state.language, // 默认选择的语言 locale: store.state.language, // 默认选择的语言
// locale: 'en_US', // 默认选择的语言 // locale: 'en_US', // 默认选择的语言

BIN
pages/markets/.DS_Store

Binary file not shown.

94
pages/markets/index.vue

@ -8,13 +8,15 @@
</view> </view>
<!-- 列表 --> <!-- 列表 -->
<view class="coinList"> <view class="coinList">
<view class="coin" v-for="(item, index) in 20" :key="index" @click="goto(item)"> <view class="coin" v-for="(item, index) in symbolList" :key="index" @click="goto(item)">
<view class="icon"> <view class="icon">
<u-icon name="../../static/maskets/bye.png" size="40rpx" width="40rpx"></u-icon> <u-icon :name="BASE_URL+item.coinSymbol+'.png'" size="40rpx" width="40rpx"></u-icon>
</view>
<view class="name">{{item.pair}}</view>
<view class="price">{{ item.price}}</view>
<view class="priceChange" :class="{ 'down': item.percent< 0 }">
{{item.percent>=0?'+'+item.percent:item.percent}}%
</view> </view>
<view class="name">BTC/USDT</view>
<view class="price">{{ 5145 * index * index * index }}</view>
<view class="priceChange" :class="{ 'down': index % 2 === 0 }">500.30%</view>
</view> </view>
</view> </view>
<!-- tabBar --> <!-- tabBar -->
@ -23,20 +25,29 @@
</template> </template>
<script> <script>
export default { export default {
name: 'markets', name: 'markets',
data() { data() {
return { return {
BASE_URL: '',
symbolList: [],
websock: null,
websockId: null
} }
}, },
onLoad() { onLoad() {
this.BASE_URL = this.$constant.BASE_URL + '/coins/';
this.getSymbolGroup();
this.initWebSocket()
}, },
onShow() { onShow() {
}, },
onHide() { onHide() {
this.unsubWebSocket();
},
onUnload() {
this.unsubWebSocket();
}, },
computed: { computed: {
i18n() { i18n() {
@ -44,21 +55,80 @@ export default {
} }
}, },
methods: { methods: {
getSymbolGroup() {
const symbolGroup = this.$api.symbolGroup({
"model": "contract"
});
symbolGroup.then(res => {
this.symbolList = res.USDT
})
.catch(e => {
console.log(e)
uni.showToast({
title: e,
icon: 'none',
duration: 2500
})
})
},
subWebSocket() {
const data = {
event: 'sub',
type: 'pairsgroup',
id: this.websockId,
channel: ["market.pairsgroup"]
};
this.websock.webSocketSendMsg(data)
console.log("websocket发送", data);
},
unsubWebSocket() {
const data = {
event: 'un_sub',
type: 'pairsgroup',
id: this.websockId,
channel: ["market.pairsgroup"]
};
this.websock.webSocketSendMsg(data)
},
initWebSocket() {
this.websock = new this.$websocket(this.$constant.WSSURL) // xxx URL
var that = this
this.websock.getWebSocketMsg(data => {
console.log(data, 1111)
if (data.channel === 'conn') {
that.websockId = data.data
that.subWebSocket();
} else if (data.channel === 'market.pairsgroup') {
that.symbolList = data.data.USDT;
}
});
},
/** /**
* 跳转 * 跳转
*/ */
goto(data) { goto(data) {
uni.setStorageSync('symbol', data);
uni.navigateTo({ uni.navigateTo({
url: '/pages/markets/trade', url: '/pages/markets/trade',
}); });
}, },
} }
} }
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>
.main { .main {
padding-bottom: 198rpx; // TabBar padding-bottom: 198rpx; // TabBar
.nav-head { .nav-head {
@ -163,5 +233,5 @@ export default {
} }
</style> </style>

288
pages/markets/kLine.vue

@ -25,9 +25,21 @@
</view> </view>
</view> </view>
</view> </view>
<view class="tab">
<view class="item" :class="{ select: type === 0 }" @click="onChangeType(0)">1M
</view>
<view class="item" :class="{ select: type === 1 }" @click="onChangeType(1)">30M
</view>
<view class="item" :class="{ select: type === 2 }" @click="onChangeType(2)">60M
</view>
<view class="item" :class="{ select: type === 3 }" @click="onChangeType(3)">1D
</view>
<view class="item" :class="{ select: type === 3 }" @click="onChangeType(3)">30D
</view>
</view>
<!-- K线图 --> <!-- K线图 -->
<view class="kline" id="kline" :kdata="kdata" :change:kdata="klineE.receive" <view class="kline" id="kline" :kdata="kdata" :change:kdata="klineE.receive"
style="height:1000rpx;color:aliceblue "> style="height:500rpx;width: 100%;position: relative; padding: 0px; margin: 0px; border-width: 0px; cursor: default;">
</view> </view>
<!-- 买卖挂牌表 --> <!-- 买卖挂牌表 -->
@ -79,15 +91,18 @@
</template> </template>
<script> <script>
import ktest from '@/utils/ktest.js' import ktest from '@/utils/ktest.js'
export default { export default {
name: "trade", name: "trade",
components: { ktest }, components: {
ktest
},
data() { data() {
return { return {
buyList: 7, buyList: 7,
sellList: 9, sellList: 9,
kdata: [] kdata: [],
type:1
}; };
}, },
@ -100,7 +115,7 @@ export default {
this.kdata = this.splitData(ktest.JSON); this.kdata = this.splitData(ktest.JSON);
// console.log(this.kdata, 1111) // console.log(this.kdata, 1111)
}, },
onShow() { }, onShow() {},
methods: { methods: {
into() { into() {
@ -135,16 +150,29 @@ export default {
uni.navigateTo({ uni.navigateTo({
url, url,
}); });
},
openBtnClick(){
// let categoryData = [];
// let values = [];
// let volumes = [];
// this.kdata.values.pop();
// this.kdata.volumes.pop();
this.kdata.values.push([17827.33+Math.floor(Math.random()*100),
17829.73+Math.floor(Math.random()*100),
17799.8+Math.floor(Math.random()*100),
17877.84+Math.floor(Math.random()*100) , 85130000+Math.floor(Math.random()*100)])
this.kdata.volumes.push([3140,1688777777,1])
this.kdata.categoryData.push('2016-06-22')
} }
}, },
} }
</script> </script>
<script module="klineE" lang="renderjs"> <script module="klineE" lang="renderjs">
let kline let kline
export default { export default {
mounted() { mounted() {
console.log('1111',this.kdata); console.log('1111', this.kdata.categoryData);
if (typeof window.echarts === 'function') { if (typeof window.echarts === 'function') {
//this.initEcharts() //this.initEcharts()
} else { } else {
@ -160,6 +188,7 @@ export default {
methods: { methods: {
receive(newValue, oldValue, ownerVm, vm) { receive(newValue, oldValue, ownerVm, vm) {
console.log('newValue', newValue) console.log('newValue', newValue)
const script = document.createElement('script'); const script = document.createElement('script');
// view www www // view www www
@ -167,6 +196,7 @@ export default {
script.onload = this.upData.bind(this); script.onload = this.upData.bind(this);
document.head.appendChild(script); document.head.appendChild(script);
}, },
calculateMA(dayCount, data) { calculateMA(dayCount, data) {
@ -184,104 +214,45 @@ export default {
} }
return result; return result;
}, },
upData(myChart){ upData(myChart) {
const upColor = '#00C873'; const upColor = '#00C873';
const downColor = '#FF3750'; const downColor = '#FF3750';
var chartDom = document.getElementById('kline'); var chartDom = document.getElementById('kline');
var myChart = echarts.init(chartDom); if(!this.is){
this.myChart = echarts.init(chartDom);
}
this.is=true;
var option; var option;
myChart.setOption( this.myChart.setOption(
(option = { (option = {
animation: false,
legend: {
bottom: 10,
left: 'center',
data: []
},
tooltip: { tooltip: {
trigger: 'axis', trigger: 'axis',
axisPointer: { axisPointer: {
type: 'cross' animation: false,
}, type: 'cross',
borderWidth: 1, lineStyle: {
borderColor: '#ccc', width: 1,
padding: 10, opacity: 3
textStyle: {
color: '#ffffff'
},
position: function (pos, params, el, elRect, size) {
const obj = {
top: 10
};
obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 30;
return obj;
}
// extraCssText: 'width: 170px'
},
axisPointer: {
link: [
{
xAxisIndex: 'all'
}
],
label: {
backgroundColor: '#fff'
}
},
toolbox: {
feature: {
dataZoom: {
yAxisIndex: false
},
brush: {
type: ['lineX', 'clear']
}
} }
},
brush: {
xAxisIndex: 'all',
brushLink: 'all',
outOfBrush: {
colorAlpha: 0.1
} }
}, },
visualMap: { xAxis: [{
type: 'category',
data: this.kdata.categoryData,
boundaryGap: false,
axisLine: {
show: false, show: false,
seriesIndex: 5, onZero: false
dimension: 2,
pieces: [
{
value: 1,
color: downColor
}, },
{
value: -1, axisTick: {
color: upColor show: false
}
]
}, },
grid: [ splitLine: {
{ show: false
left: '10%',
right: '0%',
height: '50%',
backgroundColor:'transparent',
}, },
{
left: '10%',
right: '0%',
top: '63%',
height: '16%'
}
],
xAxis: [
{
type: 'category',
data: this.kdata.categoryData,
boundaryGap: false,
axisLine: {show: false, onZero: false },
axisTick: { show: false },
splitLine: { show: false },
min: 'dataMin', min: 'dataMin',
max: 'dataMax', max: 'dataMax',
axisPointer: { axisPointer: {
@ -293,26 +264,40 @@ export default {
gridIndex: 1, gridIndex: 1,
data: this.kdata.categoryData, data: this.kdata.categoryData,
boundaryGap: false, boundaryGap: false,
axisLine: { onZero: false }, axisLine: {
axisTick: { show: false }, onZero: false
splitLine: { show: false }, },
axisLabel: { show: false }, axisTick: {
show: false
},
splitLine: {
show: false
},
axisLabel: {
show: false
},
min: 'dataMin', min: 'dataMin',
max: 'dataMax' max: 'dataMax'
} }
], ],
yAxis: [ yAxis: [{
{
scale: true, scale: true,
axisLine: { show: false },
axisTick: { show: false }, axisLine: {
show: false
},
axisTick: {
show: true
},
splitArea: { splitArea: {
show: false, show: false, // areaStyle: {
// areaStyle: {
// color: 'transparency', // color: 'transparency',
// }, // },
}, },
splitLine: { show: true, splitLine: {
show: true,
lineStyle: { lineStyle: {
// 使 // 使
color: ['#211F32'] color: ['#211F32']
@ -323,21 +308,59 @@ export default {
scale: true, scale: true,
gridIndex: 1, gridIndex: 1,
splitNumber: 2, splitNumber: 2,
axisLabel: { show: false }, axisLabel: {
axisLine: { show: false }, show: false
axisTick: { show: false }, },
splitLine: { show: false } axisLine: {
show: false
},
axisTick: {
show: false
},
splitLine: {
show: false
}
} }
], ],
dataZoom: [
visualMap: {
show: false,
seriesIndex: 1,
dimension: 2,
pieces: [{
value: 1,
color: downColor
},
{
value: -1,
color: upColor
}
]
},
grid: [{
top: '8%',
left: '50rpx',
right: '10rpx',
height: '60%',
backgroundColor: 'transparent',
},
{ {
left: '0%',
right: '0%',
top: '80%',
height: '16%'
}
],
dataZoom: [{
type: 'inside', type: 'inside',
xAxisIndex: [0, 1],
start: 98, start: 98,
end: 100 end: 100
}, },
{ {
show: true, show: false,
xAxisIndex: [0, 1], xAxisIndex: [0, 1],
type: 'slider', type: 'slider',
top: '85%', top: '85%',
@ -345,8 +368,7 @@ export default {
end: 100 end: 100
} }
], ],
series: [ series: [{
{
name: 'Dow-Jones index', name: 'Dow-Jones index',
type: 'candlestick', type: 'candlestick',
data: this.kdata.values, data: this.kdata.values,
@ -356,11 +378,24 @@ export default {
borderColor: undefined, borderColor: undefined,
borderColor0: undefined borderColor0: undefined
}, },
markLine: {
symbol: ['none', 'none'],
data: [
{
name: 'max line on close',
type: 'max',
valueDim: 'close'
}
]
},
tooltip: { tooltip: {
formatter: function (param) { formatter: function(param) {
param = param[0]; param = param[0];
return [ return [
'Date: ' + param.name + '<hr size=1 style="margin: 3px 0">', 'Date: ' + param.name +
'<hr size=1 style="margin: 3px 0">',
'Open: ' + param.data[0] + '<br/>', 'Open: ' + param.data[0] + '<br/>',
'Close: ' + param.data[1] + '<br/>', 'Close: ' + param.data[1] + '<br/>',
'Lowest: ' + param.data[2] + '<br/>', 'Lowest: ' + param.data[2] + '<br/>',
@ -385,6 +420,7 @@ export default {
}), }),
true true
); );
} }
}, },
watch: { watch: {
@ -398,7 +434,7 @@ export default {
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>
.main { .main {
.header { .header {
background: #000000; background: #000000;
@ -462,11 +498,26 @@ export default {
} }
} }
.tab {
display: flex;
background:#000000;
.item {
height: 64rpx;
line-height: 64rpx;
flex: 1;
font-size: 24rpx;
text-align: center;
&.select {
background: rgba(0, 232, 162,0.3);
border-radius: 19px;
}
}
}
.kline { .kline {
margin-top: 20rpx;
padding-left: 32rpx;
padding-right: 28rpx;
background: #000000; background: #000000;
} }
@ -483,6 +534,7 @@ export default {
font-size: 24rpx; font-size: 24rpx;
.box { .box {
padding-left: 32rpx;
flex: 1; flex: 1;
overflow: hidden; overflow: hidden;
height: 450rpx; height: 450rpx;
@ -583,5 +635,5 @@ export default {
} }
} }
} }
</style> </style>

156
pages/markets/trade.vue

@ -2,7 +2,7 @@
<view class="main"> <view class="main">
<!-- nav --> <!-- nav -->
<navigation :showBack="false"> <navigation :showBack="false">
<view class="leftMenuBtn" @click="popupShow = true">{{ 'BTC/USDT' }}</view> <view class="leftMenuBtn" @click="popupShow = true">{{symbol.pair}}</view>
<view slot="right" class="right" @click="goto('kLine')"></view> <view slot="right" class="right" @click="goto('kLine')"></view>
</navigation> </navigation>
<view class="content"> <view class="content">
@ -30,10 +30,12 @@
<view class="coinList"> <view class="coinList">
<scroll-view scroll-y="true" style="height: 86vh;" scroll-with-animation="true" <scroll-view scroll-y="true" style="height: 86vh;" scroll-with-animation="true"
@touchmove.stop.prevent=""> @touchmove.stop.prevent="">
<view class="coin" v-for="(item, index) in 20" :key="index" @click="switchTo(item)"> <view class="coin" v-for="(item, index) in symbolList" :key="index" @click="switchTo(item)">
<view class="name">BTC/USDT</view> <view class="name">{{item.pair}}</view>
<view class="price">{{ 5145 * index * index * index }}</view> <view class="price">{{ item.price}}</view>
<view class="priceChange" :class="{ 'down': index % 2 === 0 }">500.30%</view> <view class="priceChange" :class="{ 'down': item.percent< 0 }">
{{item.percent>=0?'+'+item.percent:item.percent}}%
</view>
</view> </view>
</scroll-view> </scroll-view>
@ -46,11 +48,16 @@
</template> </template>
<script> <script>
export default { export default {
name: "trade", name: "trade",
data() { data() {
return { return {
popupShow: false, popupShow: false,
symbolList: [],
symbol: null,
marketDetail:null,
bboList:[],
tradeList:[]
}; };
}, },
computed: { computed: {
@ -59,9 +66,137 @@ export default {
}, },
}, },
onLoad() { onLoad() {
this.symbol=uni.getStorageSync('symbol');
if(this.symbol!=null){
this.getMarketDetail(this.symbol.symbol)
this.getBboList(this.symbol.symbol);
this.getTradeList(this.symbol.symbol);
}
this.getSymbolGroup();
this.initWebSocket();
},
onShow() {
console.log(11111, uni.getStorageSync('symbol'));
}, },
onShow() { },
methods: { methods: {
getTradeList(symbol){
const tradeList = this.$api.tradeList({
"symbol": symbol
});
tradeList.then(res => {
this.tradeList = res
})
.catch(e => {
console.log(e)
uni.showToast({
title: e,
icon: 'none',
duration: 2500
})
})
},
getBboList(symbol){
const bboList = this.$api.bboList({
"symbol": symbol
});
bboList.then(res => {
this.bboList = res
})
.catch(e => {
console.log(e)
uni.showToast({
title: e,
icon: 'none',
duration: 2500
})
})
},
getMarketDetail(symbol){
const marketDetail = this.$api.marketDetail({
"symbol": symbol
});
marketDetail.then(res => {
this.marketDetail = res
})
.catch(e => {
console.log(e)
uni.showToast({
title: e,
icon: 'none',
duration: 2500
})
})
},
getSymbolGroup() {
const symbolGroup = this.$api.symbolGroup({
"model": "contract"
});
symbolGroup.then(res => {
this.symbolList = res.USDT
if(this.symbol==null){
this.symbol=this.symbolList[0]
}
})
.catch(e => {
console.log(e)
uni.showToast({
title: e,
icon: 'none',
duration: 2500
})
})
},
initWebSocket() {
this.websock = new this.$websocket(this.$constant.WSSURL) // xxx URL
var that = this
this.websock.getWebSocketMsg(data => {
if (data.channel === 'conn') {
that.websockId = data.data
that.subpairsgroup();
} else if (data.channel === 'market.pairsgroup') {
that.symbolList = data.data.USDT;
}else if (data.channel === 'market.pairsgroup') {
that.symbolList = data.data.USDT;
}
});
},
//
subpairsgroup(){
this.subWebSocket('pairsgroup',['market.pairsgroup'])
},
subWebSocket(type,channel) {
const data = {
event: 'sub',
type: type,
id: this.websockId,
channel: channel
};
this.websock.webSocketSendMsg(data)
console.log("websocket发送", data);
},
unsubWebSocket(type,channel) {
const data = {
event: 'un_sub',
type: type,
id: this.websockId,
channel: channel
};
this.websock.webSocketSendMsg(data)
},
depthChange(e) { depthChange(e) {
console.log(e); console.log(e);
}, },
@ -83,14 +218,15 @@ export default {
*/ */
switchTo(item) { switchTo(item) {
this.popupShow = false; this.popupShow = false;
this.symbol=item;
} }
}, },
} }
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>
.main { .main {
padding-bottom: 198rpx; // TabBar padding-bottom: 198rpx; // TabBar
.leftMenuBtn { .leftMenuBtn {
@ -241,5 +377,5 @@ export default {
} }
</style> </style>

13
utils/axios.js

@ -29,9 +29,10 @@ service.interceptors.request.use(
mask: true mask: true
}) })
} }
if (config.url.indexOf('market') > -1) { if (config.url.indexOf('market') > -1) {
// #ifdef H5 // #ifdef H5
baseURL = constant.H5_MARKET_URL; config.baseURL = constant.H5_MARKET_URL;
// #endif // #endif
// #ifdef APP-PLUS // #ifdef APP-PLUS
config.baseURL = Vue.prototype.MARKET_URL; config.baseURL = Vue.prototype.MARKET_URL;
@ -138,19 +139,16 @@ service.interceptors.response.use(res => {
// console.log(res) // console.log(res)
// console.log(res.data) // console.log(res.data)
// console.log(res.data.data[0].nameAlias) // console.log(res.data.data[0].nameAlias)
if (res.success || res.errCode === 'USER.0017') { if (res.code===0||res.success) {
return res.data; return res.data;
} }
if(res.errMsg=='No customer service is online'&&res.errCode=='SYS.0012'){
return res;
}
else {
uni.showToast({ uni.showToast({
title: res.errMsg, title: res.errMsg,
icon: 'none', icon: 'none',
duration: 1500 duration: 1500
}) })
if (res.errCode === 'USER.0010') { if (res.errCode === 'SYS.0006') {
uni.setStorageSync('ticket',null); uni.setStorageSync('ticket',null);
uni.removeStorage({ uni.removeStorage({
key: 'logInfo', key: 'logInfo',
@ -178,7 +176,6 @@ service.interceptors.response.use(res => {
} }
uni.$emit('refreshQrCode') uni.$emit('refreshQrCode')
return Promise.reject(res.errMsg); return Promise.reject(res.errMsg);
}
}, error => { }, error => {
uni.hideLoading(); uni.hideLoading();
return Promise.reject(error) return Promise.reject(error)

184
utils/websocket.js

@ -0,0 +1,184 @@
class WebSocketClass {
constructor(url) {
this.lockReconnect = false; // 是否开始重连
this.wsUrl = ""; // ws 地址
this.globalCallback = null; // 回调方法
this.userClose = false; // 是否主动关闭
this.createWebSocket(url);
}
createWebSocket(url) {
// #ifdef H5
if (typeof(WebSocket) === 'undefined') {
this.writeToScreen("您的浏览器不支持WebSocket,无法获取数据");
return false
}
// #endif
// #ifdef APP-PLUS
if (typeof(uni.connectSocket) === 'undefined') {
this.writeToScreen("您的浏览器不支持WebSocket,无法获取数据");
return false
}
// #endif
this.wsUrl = url;
try {
// 创建一个this.ws对象【发送、接收、关闭socket都由这个对象操作】
// #ifdef H5
this.ws = new WebSocket(this.wsUrl);
this.initEventHandle();
// #endif
// #ifdef APP-PLUS
let that = this
this.ws = uni.connectSocket({
url: this.wsUrl,
success(data) {
console.log("websocket连接成功");
that.initEventHandle();
},
});
// #endif
} catch (e) {
this.reconnect(url);
}
}
// 初始化
initEventHandle() {
/**
* 监听WebSocket连接打开成功
*/
// #ifdef H5
this.ws.onopen = (event) => {
console.log("WebSocket连接打开");
};
// #endif
// #ifdef APP-PLUS
this.ws.onOpen(res => {
console.log('WebSocket连接打开');
});
// #endif
/**
* 连接关闭后的回调函数
*/
// #ifdef H5
this.ws.onclose = (event) => {
if (!this.userClose) {
this.reconnect(this.wsUrl); //重连
}
};
// #endif
// #ifdef APP-PLUS
this.ws.onClose(() => {
if (!this.userClose) {
this.reconnect(this.wsUrl); //重连
}
});
// #endif
/**
* 报错时的回调函数
*/
// #ifdef H5
this.ws.onerror = (event) => {
if (!this.userClose) {
this.reconnect(this.wsUrl); //重连
}
};
// #endif
// #ifdef APP-PLUS
this.ws.onError(() => {
if (!this.userClose) {
this.reconnect(this.wsUrl); //重连
}
});
// #endif
/**
* 收到服务器数据后的回调函数
*/
// #ifdef H5
this.ws.onmessage = (event) => {
this.globalCallback(JSON.parse(event.data))
};
// #endif
// #ifdef APP-PLUS
this.ws.onMessage(event => {
this.globalCallback(JSON.parse(event.data))
});
// #endif
}
// 关闭ws连接回调
reconnect(url) {
if (this.lockReconnect) return;
this.ws.close();
this.lockReconnect = true; // 关闭重连,没连接上会一直重连,设置延迟避免请求过多
setTimeout(() => {
this.createWebSocket(url);
this.lockReconnect = false;
}, 1000);
}
// 发送信息方法
webSocketSendMsg(msg) {
// #ifdef H5
this.ws && this.ws.send(JSON.stringify(msg));
// #endif
// #ifdef APP-PLUS
this.ws && this.ws.send({
data: JSON.stringify(msg),
success() {
console.log("消息发送成功");
},
fail(err) {
console.log("关闭失败", err)
}
});
// #endif
}
// 获取ws返回的数据方法
getWebSocketMsg(callback) {
this.globalCallback = callback
}
// 关闭ws方法
closeSocket() {
if (this.ws) {
this.userClose = true;
this.ws.close({
success(res) {
console.log("关闭成功", res)
},
fail(err) {
console.log("关闭失败", err)
}
});
}
}
writeToScreen(massage) {
console.log(massage);
}
}
export default WebSocketClass;
Loading…
Cancel
Save