vue 配合webSocket和elementui notify设计警告框

websocket基本模式,代码如下

先在data定义以下字段:

data() {
    return {
      websock: null,
      notifications: {}
    };
  },
initWebSocket() {
      const userInfo = sessionStorage.getItem("userInfo");
      // console
      if (!userInfo) {
        return
      } else {
        const userId = JSON.parse(userInfo).id;
        // console.log("已登录");
        // this.open();
        //初始化weosocket
        const wsuri = `ws://${this.$root.ipUrl}:8495/wsserver/${userId}`;
        this.websock = new WebSocket(wsuri);
        this.websock.onmessage = this.websocketonmessage;
        this.websock.onopen = this.websocketonopen;
        this.websock.onerror = this.websocketonerror;
      }
    },
    websocketonopen() {
      // console.log("链接成功");
      //连接建立之后执行send方法发送数据
    },
    websocketonerror() {
      //连接建立失败重连
      this.initWebSocket();
    },
    websocketonmessage(e) {
      if (this.$route.path == "/login") {
      } else {
        this.open(e.data);
      }
      //数据接收
    },
    websocketsend(Data) {
      //数据发送
      this.websock.send(Data);
    },
    websocketclose(e) {
      //关闭
      console.log("断开连接", e);
    },
    open(message) {
      if (message == "连接成功") {
      } else {
        this.audioBtn(); // 播放音乐
        var messageCopy = JSON.parse(message);
        var arr = Object.keys(this.notifications).length;
        if (messageCopy.type == 1) {
          let notify = this.$notify({
            title: "警告:",
            message: messageCopy.message,
            duration: 60000,
            customClass: "warningCss" // 自定义样式
            // offset: 80 // 位置
          });
        } else if (messageCopy.type == 2) {
          let notify = this.$notify({
            title: "警告:",
            message: messageCopy.message,
            duration: 60000,
            customClass: "earlyCss" //自定义样式
            // offset: 80 // 位置
          });
        }
        this.notifications["message" + arr] = notify;
      }
    }

关闭弹出框

this.$notify.close() // 关闭

关闭多个

// 在上述的弹出框中,每一个都保存下来
let notify = this.$notify({
    title: "警告:",
    message: messageCopy.message,
    duration: 60000,
    customClass: "earlyCss" //自定义样式
    // offset: 80 // 位置
  });
  this.notifications["message" + arr] = notify; // 都存储在notifications中
  // 清除全部弹出框
  for (let key in this.notifications) {
      this.notifications[key].close();
       delete this.notifications[key];
     }

离开页面清除websocket

this.websock.close();

你可能感兴趣的:(elementUi,vue,webSocket)