溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

vue如何實(shí)現(xiàn)發(fā)送websocket請(qǐng)求和http post請(qǐng)求

發(fā)布時(shí)間:2021-07-20 14:13:17 來源:億速云 閱讀:1398 作者:小新 欄目:web開發(fā)

這篇文章主要介紹vue如何實(shí)現(xiàn)發(fā)送websocket請(qǐng)求和http post請(qǐng)求,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!

先給大家介紹下vue發(fā)送websocket請(qǐng)求和http post請(qǐng)求

直接上代碼:

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;
        // 斷開重連機(jī)制,嘗試發(fā)送消息,捕獲異常發(fā)生時(shí)重連
        this.timer = setInterval(() => {
          try {
            that.stompClient.send("test");
          } catch(err) {
            console.log("斷線了: " + err);
            that.connection();
          }
        }, 5000);
      },
      connection() {
        // 建立連接對(duì)象
        let socket = new SockJS('http://XXX.XX.XX.XXX:8081/energy-system-websocket');
        // 獲取STOMP子協(xié)議的客戶端對(duì)象
        this.stompClient = Stomp.over(socket);
        // 定義客戶端的認(rèn)證信息,按需求配置
        let headers = {
          access_token: "92c31bd5-ae43-4f25-9aad-c4eb1a92d61d"
          //          Authorization: ''
        }
        // 向服務(wù)器發(fā)起websocket連接
        this.stompClient.connect(headers, () => {
          this.stompClient.subscribe('/user/topic/data', (msg) => { // 訂閱服務(wù)端提供的某個(gè)topic
              console.log('廣播成功')
              //            console.log(msg); // msg.body存放的是服務(wù)端發(fā)送給我們的信息
              console.log(msg.body);
              this.newsData = JSON.parse(msg.body);

            }, headers),
            this.stompClient.subscribe('/user/topic/alarm', (msg) => { // 訂閱服務(wù)端提供的某個(gè)topic
              console.log('廣播告警成功')
              //console.log(msg); // msg.body存放的是服務(wù)端發(fā)送給我們的信息
              console.log(msg.body);
              this.newsData = JSON.parse(msg.body);

            }, headers);
          this.stompClient.subscribe('/user/topic/cmd_ack', (msg) => { // 訂閱服務(wù)端提供的某個(gè)topic
            console.log('下控指令應(yīng)答成功')
            //console.log(msg); // msg.body存放的是服務(wù)端發(fā)送給我們的信息
            console.log(msg.body);
            this.newsData = JSON.parse(msg.body);

          }, headers);

          this.stompClient.subscribe('/user/topic/response', (msg) => { //指令的應(yīng)答(僅表示服務(wù)端接收成功或者失?。?
            console.log('SEND指令的應(yīng)答成功')
            //console.log(msg); // msg.body存放的是服務(wù)端發(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)控的測(cè)點(diǎ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ā)生錯(cuò)誤時(shí)的處理函數(shù)
          console.log('失敗')
          console.log(err);
        });
      }, //連接 后臺(tái)
      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("合閘失?。≌?qǐng)聯(lián)系管理員");
            }379           })
          .catch(error => {
            console.log(error)
          })
      },
      fenzha() {
        alert("分閘"); //3#樓3AA-4_分閘
      }
    },
    mounted() {
      this.initWebSocket();
    },
    beforeDestroy: function() { // 頁面離開時(shí)斷開連接,清除定時(shí)器
      this.disconnect();
      clearInterval(this.timer);
    },
    created() {

    }
  }
</script>

在main.js設(shè)置全局http地址:

Axios.defaults.baseURL = 'http://XXX.XXX.XX.XXX:9001';
Axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

在main.js中設(shè)置header中token值:

// 添加請(qǐng)求攔截器
Axios.interceptors.request.use(function(config) {
  config.headers.access_token = "add7c097-f12b-40fe-8e48-6fe1f2120fa5";
  //  config.headers.Authorization = localStorage.token; //將token設(shè)置成請(qǐng)求頭
  console.log("請(qǐng)求============" + config);
  // 在發(fā)送請(qǐng)求之前做些什么
  return config;
}, function(error) {
  // 對(duì)請(qǐng)求錯(cuò)誤做些什么
  return Promise.reject(error);
});

vue如何實(shí)現(xiàn)發(fā)送websocket請(qǐng)求和http post請(qǐng)求

數(shù)據(jù)刷起來!

ps:下面給大家介紹下vue websocket 請(qǐng)求

首先寫一個(gè)公共方法

socket.js

function getSocket(url, params, callback) {
  let socket;
  if (typeof (WebSocket) === 'undefined') {
    console.log('您的瀏覽器不支持WebSocket');
  } else {
    console.log('您的瀏覽器支持WebSocket');
    // 初始化 WebSocket 對(duì)象,指定要連接的服務(wù)器地址與端口建立連接
    socket = new WebSocket(url);
    // 打開事件
    socket.onopen = function() {
      console.log('Socket 已打開');
      socket.send(params);
    };
    // 獲得消息事件
    socket.onmessage = function(msg) {
      // 發(fā)現(xiàn)消息進(jìn)入, 開始處理前端觸發(fā)邏輯
      callback(msg, socket);
    };
    // 關(guān)閉事件
    socket.onclose = function() {
      console.log('Socket 已關(guān)閉');
    };
    // 發(fā)生了錯(cuò)誤事件
    socket.onerror = function() {
      console.log('Socket 發(fā)生了錯(cuò)誤,請(qǐng)刷新頁面');
      // 此時(shí)可以嘗試刷新頁面
    };
  }
}
export {
  getSocket
};

使用

test.vue

<script>
import {getSocket} from '@/utils/socket.js';
export default {
  data() {
    return {
      wsData: {}, // 保存 websocket 數(shù)據(jù)對(duì)象
      form: { // 表單
        name: '',
        age: ''
      }
    }
  },
  beforeDestroy() {
    this.wsData.close(); // 關(guān)閉 websocket
  },
  created() {
    this.getSocketData();
  },
  methods: {
    // 獲取數(shù)據(jù)
    getSocketData() {
      let params = this.form;
      getSocket(
        `ws://path`,
        JSON.stringify(params),
        (data, ws) => {
          console.log(data, ws);
          // 保存數(shù)據(jù)對(duì)象, 以便發(fā)送消息
          this.wsData = ws;
        }
      );
    },
    // 發(fā)送數(shù)據(jù)
    sendSocketData() {
      let params = this.form;
      params.name = 'xx';
      params.age= '18';
      this.wsData.send(JSON.stringify(params));
    }
  }
}
</script>

以上是“vue如何實(shí)現(xiàn)發(fā)送websocket請(qǐng)求和http post請(qǐng)求”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI