一.设置websocket标识
websock:null
二.method里面
//初始化websocket
initWebSocket(){
var _self = this;
var currentTime = new Date();
_self.websock = new WebSocket("ws://127.0.0.1:8088/chatsocket?openid="+_self.openid+"&date="+currentTime);
_self.websock.onopen = this.websocketonopen;
_self.websock.onerror = this.websocketonerror;
_self.websock.onmessage = this.websocketonmessage;
_self.websock.onclose = this.websocketclose;
},
websocketonopen(){
var _self = this;
var param = {};
param["openid"] = _self.openid;
param["text"] = "Hi";
param["uuid"] = _self.uuid;
param = JSON.stringify(param);
this.websocketsend(param);
},
websocketsend(agentData){//数据发送
this.websock.send(agentData);
},
websocketonerror(e){
var _self = this;
_self.websock = null;
},
websocketonmessage(e){
var msg = JSON.parse(e.data);
var obj = {};
obj['id'] = 1;
obj['message'] = msg.Text;
//存我发出的消息
this.$store.commit('addDialog',obj);
},
//销毁websocket
websocketclose(){
var _self = this;
_self.websock = null;
},
三.mounted调用
mounted : function() {
_self.initWebSocket();
}