vue2.0
<script>
import store from '@/store/'
export default {
data() {
return {
}
},
mounted() {
//初始化websocket
this.initWebSocket()
},
destroyed: function () { // 离开页面生命周期函数
this.websocketclose();
},
methods: {
initWebSocket: function () { // 建立连接
// WebSocket与普通的请求所用协议有所不同,ws等同于http,wss等同于https
var userId = store.getters.userInfo.id;
var url = window._CONFIG['domianURL'].replace("https://","ws://").replace("http://","ws://")+"/websocket/"+userId;
this.websock = new WebSocket(url);
this.websock.onopen = this.websocketonopen;
this.websock.send = this.websocketsend;
this.websock.onerror = this.websocketonerror;
this.websock.onmessage = this.websocketonmessage;