首先安裝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
pongTimeout: 1800000,reconnectTimeout: 100
});
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
});
}
},
},
