首先安装npm install --save websocket-heartbeat-js@^1.0.7
在main.js中 引入并挂载全局方法
import WebsocketHeartbeatJs from 'websocket-heartbeat-js';if (JSON.parse(getStore('userInfo'))!= null) { let userId = JSON.parse(getStore('userInfo')).id; let websocketHeartbeatJs = new WebsocketHeartbeatJs({ // url: 'ws://192.168.0.68:8888/websocket/' + userId url: 'ws://192.168.0.22:8888/websocket/' + userId }); Vue.prototype.websocketHeartbeatJs = websocketHeartbeatJs;}
在app.vue中 建立连接
mounted() { // console.log(JSON.parse(this.getStore("userInfo")),'--------JSON.parse(this.getStore("userInfo"))-------') if (JSON.parse(this.getStore("userInfo")).id != "") { // console.log(JSON.parse(this.getStore("userInfo")).id); if ("WebSocket" in window) { this.websocketHeartbeatJs.onopen = function() {}; var that = this; this.websocketHeartbeatJs.onmessage = function(e) { // console.log(JSON.parse(e.data),'-------------JSON.parse(e.data)-----------------'); that.$store.state.websocketMsg = JSON.parse(e.data); 在store中存放webscoket信息 // console.log(that.$store.state.websocketMsg); }; this.websocketHeartbeatJs.onreconnect = function() {}; } else { alert("当前浏览器 Not support websocket"); } } },
在vue组件中使用
computed: { websocketInfo() { return this.$store.state.websocketMsg; //创建完成时存在store中的信息 } }, watch: { websocketInfo: function (nv, ov) { console.log(nv); this.websocketSuccess = nv.result.success; this.websocketMsg = nv.result.message; console.log(this.websocketSuccess, '-----------websocketSuccess----------'); console.log(this.websocketMsg, '----------websocketMsg-------------'); // console.log(nv.result.result.error.code); if (this.websocketSuccess == true && this.websocketMsg == "true") { // 创建云盘成功后挂载云主机 if (nv.result.result.inventory != undefined) { this.diskid = nv.result.result.inventory.uuid; this.id = this.$store.state.vmId; } this.$Notice.destroy({ name: "warning", duration: 1 }); var imageNames = this.vmName == "" ? "" : "'" + this.vmName + "'"; this.$Notice.success({ title: this.operation == "" ? this.$store.state.operationed : "云盘"+ imageNames + this.operation +"成功" }); this.getImagesList(this.pageSize, this.pageNumber); this.$refs.child.getinfo(); this.$refs.child.chishihua(); this.value2 = true; // 创建完成挂载云主机 if(this.operation == '' && this.$store.state.operationed == '创建镜像成功'){ this.guazai(); }; this.operation == "" ; } else if ( this.websocketSuccess == true && this.websocketMsg == "false" ) { var str = nv.result.result.error.details; // str = str.split("不")[0]; // console.log(str); this.$Notice.warning({ title: str }); } else if ( this.websocketSuccess == true && this.websocketMsg == "" ) { this.$Notice.warning({ title: this.$store.state.operationed + "创建中", duration: 1 }); } }, },