vue發(fā)送websocket請求和http post請求的實例代碼
更新時間:2019年07月11日 11:42:12 作者:gh786395613
這篇文章主要介紹了vue發(fā)送websocket請求和http post請求的方法,本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值 ,需要的朋友可以參考下
先給大家介紹下vue發(fā)送websocket請求和http post請求
直接上代碼:
pdf.vue
<script>
import SockJS from 'sockjs-client';
import Stomp from 'stompjs';
import qs from "qs"
export default {
name: "pdf",
data() {
return {
newsData: [],
tagGuid_mx: "",
tagGuid_4AA_Ia: "",
tagGuid_4AA_P: "",
tagGuid_4AA_Q: "", 49 tagGuid_1AA_6_Ib: "",
tagGuid_1AA_6_Ic: "",
tagGuid_pdfwd: "",
tagGuid_pdfsd: "",
stompClient: '',
timer: '',
visibilityHeZha: "hidden",
visibilityFenZha: "hidden",
hezhaData:[]
}
},
methods: {
initWebSocket() {
this.connection();
let that = this;
// 斷開重連機制,嘗試發(fā)送消息,捕獲異常發(fā)生時重連
this.timer = setInterval(() => {
try {
that.stompClient.send("test");
} catch(err) {
console.log("斷線了: " + err);
that.connection();
}
}, 5000);
},
connection() {
// 建立連接對象
let socket = new SockJS('http://XXX.XX.XX.XXX:8081/energy-system-websocket');
// 獲取STOMP子協(xié)議的客戶端對象
this.stompClient = Stomp.over(socket);
// 定義客戶端的認證信息,按需求配置
let headers = {
access_token: "92c31bd5-ae43-4f25-9aad-c4eb1a92d61d"
// Authorization: ''
}
// 向服務器發(fā)起websocket連接
this.stompClient.connect(headers, () => {
this.stompClient.subscribe('/user/topic/data', (msg) => { // 訂閱服務端提供的某個topic
console.log('廣播成功')
// console.log(msg); // msg.body存放的是服務端發(fā)送給我們的信息
console.log(msg.body);
this.newsData = JSON.parse(msg.body);
}, headers),
this.stompClient.subscribe('/user/topic/alarm', (msg) => { // 訂閱服務端提供的某個topic
console.log('廣播告警成功')
//console.log(msg); // msg.body存放的是服務端發(fā)送給我們的信息
console.log(msg.body);
this.newsData = JSON.parse(msg.body);
}, headers);
this.stompClient.subscribe('/user/topic/cmd_ack', (msg) => { // 訂閱服務端提供的某個topic
console.log('下控指令應答成功')
//console.log(msg); // msg.body存放的是服務端發(fā)送給我們的信息
console.log(msg.body);
this.newsData = JSON.parse(msg.body);
}, headers);
this.stompClient.subscribe('/user/topic/response', (msg) => { //指令的應答(僅表示服務端接收成功或者失敗)
console.log('SEND指令的應答成功')
//console.log(msg); // msg.body存放的是服務端發(fā)送給我們的信息
console.log(msg.body);
this.newsData = JSON.parse(msg.body);
this.newsData = this.newsData.data;
console.log(this.newsData);
for(var i = 0; i < this.newsData.length; i++) {
//母線uab
if(this.newsData[i].tagGuid == "a3a95bf3-fef8-454e-9175-19a466e40c3d") {
this.tagGuid_mx = this.newsData[i].value != '' ? this.newsData[i].value.toFixed(2) : ""
}
//電容柜4AA_Ia
if(this.newsData[i].tagGuid == "4cf6e256-6c3a-4853-a087-dfd263916dab") {
this.tagGuid_4AA_Ia = this.newsData[i].value
}
//電容柜4AA_P
if(this.newsData[i].tagGuid == "52e8265a-0a20-4e3b-a670-14a8df373bf7") {
this.tagGuid_4AA_P = this.newsData[i].value
}
//電容柜4AA_Q
if(this.newsData[i].tagGuid == "ef369a17-0bbd-4295-8ac7-816c23fcb065") {
this.tagGuid_4AA_Q = this.newsData[i].value != '' ? this.newsData[i].value.toFixed(2) : 0
}276 //配電房溫度
if(this.newsData[i].tagGuid == "ead49446-07f9-43b7-a4ce-cd974d53728e") {
this.tagGuid_pdfwd = this.newsData[i].value
}
//配電房濕度
if(this.newsData[i].tagGuid == "baaf1733-124e-46fd-9d58-c069b747317a") {
this.tagGuid_pdfsd = this.newsData[i].value
}
}
}, headers);
this.stompClient.send("/app/monitor/subTagGuid", // # 訂閱需要監(jiān)控的測點ID
headers,
JSON.stringify({
"stationCode": "00013",
"tagGuids": [
"a3a95bf3-fef8-454e-9175-19a466e40c3d", //
"4cf6e256-6c3a-4853-a087-dfd263916dab", //
"52e8265a-0a20-4e3b-a670-14a8df373bf7", //
"ef369a17-0bbd-4295-8ac7-816c23fcb065", //334 "baaf1733-124e-46fd-9d58-c069b747317a"
]
})
) //用戶加入接口
}, (err) => {
// 連接發(fā)生錯誤時的處理函數
console.log('失敗')
console.log(err);
});
}, //連接 后臺
disconnect() {
if(this.stompClient) {
this.stompClient.disconnect();
}
}, // 斷開連接
changeColor(evt) {
this.rect.setAttributeNS(null, "fill", "blue")
},
shl3aa4() {
this.visibilityHeZha = this.visibilityHeZha == "visibility" ? "hidden" : "visibility";
this.visibilityFenZha = this.visibilityFenZha == "visibility" ? "hidden" : "visibility";
},
shl3aa42() {
setTimeout(() => {
this.visibilityHeZha = "hidden";
this.visibilityFenZha = "hidden";
}, 1200)
},
hezha() {
//3#樓3AA-4_合閘
this.$axios.post("/energy-system/auth/monitor/ykcmd", {
checkUser: "admin",
checkPass: "123456",
stationCode:"00013",
tagGuid: "89d1d312-17be-4d20-8471-baa08ba734e0",
value: 1
})
.then(res => {
this.hezhaData=JSON.parse(res.config.data)
if(this.hezhaData.tagGuid=="89d1d312-17be-4d20-8471-baa08ba734e0" && this.hezhaData.value==1){
alert("合閘成功!");
}else{
alert("合閘失??!請聯(lián)系管理員");
}379 })
.catch(error => {
console.log(error)
})
},
fenzha() {
alert("分閘"); //3#樓3AA-4_分閘
}
},
mounted() {
this.initWebSocket();
},
beforeDestroy: function() { // 頁面離開時斷開連接,清除定時器
this.disconnect();
clearInterval(this.timer);
},
created() {
}
}
</script>
在main.js設置全局http地址:
Axios.defaults.baseURL = 'http://XXX.XXX.XX.XXX:9001'; Axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
在main.js中設置header中token值:
// 添加請求攔截器
Axios.interceptors.request.use(function(config) {
config.headers.access_token = "add7c097-f12b-40fe-8e48-6fe1f2120fa5";
// config.headers.Authorization = localStorage.token; //將token設置成請求頭
console.log("請求============" + config);
// 在發(fā)送請求之前做些什么
return config;
}, function(error) {
// 對請求錯誤做些什么
return Promise.reject(error);
});

數據刷起來!
ps:下面給大家介紹下vue websocket 請求
首先寫一個公共方法
socket.js
function getSocket(url, params, callback) {
let socket;
if (typeof (WebSocket) === 'undefined') {
console.log('您的瀏覽器不支持WebSocket');
} else {
console.log('您的瀏覽器支持WebSocket');
// 初始化 WebSocket 對象,指定要連接的服務器地址與端口建立連接
socket = new WebSocket(url);
// 打開事件
socket.onopen = function() {
console.log('Socket 已打開');
socket.send(params);
};
// 獲得消息事件
socket.onmessage = function(msg) {
// 發(fā)現消息進入, 開始處理前端觸發(fā)邏輯
callback(msg, socket);
};
// 關閉事件
socket.onclose = function() {
console.log('Socket 已關閉');
};
// 發(fā)生了錯誤事件
socket.onerror = function() {
console.log('Socket 發(fā)生了錯誤,請刷新頁面');
// 此時可以嘗試刷新頁面
};
}
}
export {
getSocket
};
使用
test.vue
<script>
import {getSocket} from '@/utils/socket.js';
export default {
data() {
return {
wsData: {}, // 保存 websocket 數據對象
form: { // 表單
name: '',
age: ''
}
}
},
beforeDestroy() {
this.wsData.close(); // 關閉 websocket
},
created() {
this.getSocketData();
},
methods: {
// 獲取數據
getSocketData() {
let params = this.form;
getSocket(
`ws://path`,
JSON.stringify(params),
(data, ws) => {
console.log(data, ws);
// 保存數據對象, 以便發(fā)送消息
this.wsData = ws;
}
);
},
// 發(fā)送數據
sendSocketData() {
let params = this.form;
params.name = 'xx';
params.age= '18';
this.wsData.send(JSON.stringify(params));
}
}
}
</script>
總結
以上所述是小編給大家介紹的vue發(fā)送websocket請求和http post請求的實例代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網站的支持!
如果你覺得本文對你有幫助,歡迎轉載,煩請注明出處,謝謝!
相關文章
electron-vue+electron-updater實現自動更新(步驟源碼)
這篇文章主要介紹了electron-vue+electron-updater實現自動更新,步驟源碼包括autoUpdater.js操控更新js文件,main.js也就是package.json內的main指向的js文件,代碼簡單易懂,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-10-10

