data(){
return{
websocket: null,
}
}
created() {
localStorage.setItem('root', process.env.API_ROOT);
},
mounted(){
//页面刚进入时开启长连接
var socketUrl = localStorage.getItem('root') + "/carweb/im/" + localStorage.getItem('message');
socketUrl = socketUrl.replace("https", "wss").replace("http", "ws");
this.initWebsocket(socketUrl);
},
methods:{
//初始化websocket
async initWebsocket(wbUrl) {
setTimeout(function () {
this.websocket = new WebSocket(wbUrl);
// 连接
this.websocket.onopen = this.websocketOpen;
// 接收数据
this.websocket.onmessage = this.websocketMessage;
// 错误
this.websocket.onerror = this.websocketError;
// 关闭
this.websocket.onclose = this.websocketclose;
}.bind(this), 0);
},
websocketclose(e) { //关闭
console.log("connection closed (" + e.code + ")");
},
websocketError(e) {
console.log('报错', e);
},
//发送请求
async websocketOpen() {
console.log('websocketOK');
},
//websocket链接成功
async websocketMessage(msg) {
// 接收数据
if (msg.data != '') {
if (this.isJSON(msg.data)) {
var obj = JSON.parse(msg.data);
if (obj.type == 'notifyEvent' && obj.data.eventMsg != '' && obj.data.event != '20' && obj.data.event != '21' && obj.data.event != '22') {
if (sessionStorage.getItem('opersid') > 0) {
if (obj.data.event == '1' || obj.data.event == '2' || obj.data.event == '3') {
//司机已接单
sessionStorage.setItem('mindate', '');
sessionStorage.setItem('seconds', 0);
sessionStorage.setItem('opersid', 2);
this.$router.push('/cfront/orders');
} else if (obj.data.event == '4' || obj.data.event == '5') {
//开始计费
sessionStorage.setItem('opersid', 4);
this.$router.push('/cfront/OnTheRoad');
} else if (obj.data.event == '6') {
//完成
sessionStorage.setItem('opersid', 0);
this.$router.push('/cfront/unpaid');
}
}
}
}
}
},
isJSON(str) {
if (typeof str == 'string') {
try {
var obj = JSON.parse(str);
if (typeof obj == 'object' && obj) {
return true;
} else {
return false;
}
} catch (e) {
// console.log('error:' + str + '!!!' + e);
return false;
}
}
// console.log('It is not a string!');
}
},
destroyed() {
window.removeEventListener('popstate', this.goBack, false);
},