VUE-WebSocket使用

235 阅读1分钟

1.创建实例

1-1 创建方法注册实例
1-2 根据实例创建相关操作方法
//methods中
initWebSocket() {
    //创建ws实例 ()里面跟的是ws接口地址
      this.websock = new WebSocket(this.websockLink)
    //ws连接成功
      this.websock.onopen = this.websocketonopen
    //ws连接发生错误
      this.websock.onerror = this.websocketonerror
    //ws数据接收
      this.websock.onmessage = this.websocketonmessage
    //关闭ws
      this.websock.onclose = this.websocketclose
 },

2.声明相关方法

//methods中
    websocketonopen() {
      console.log('WebSocket连接成功')
    },
    websocketonerror(e) {
      console.log('WebSocket连接发生错误')
      console.log(36,e);
    },
    websocketonmessage(e) {
     //返回的e实例中有data标识 需要转为js对象
      const redata=JSON.parse(e.data)
      console.log(redata);
      console.log('WebSocket信息通知')
      console.log(39,e);
    },
    websocketclose(e) {
       console.log('关闭WebSocket连接')
      console.log(44,e);
    }

3.完整代码

export default {
  components: {
  },
  data() {
    return {
      websockLink: '',
      path:"120.24.43.72:8083",
      loginId:'8aacdaea6daff39f016db36bfb010009'
    }
  },
  watch: {
      //侦听websocklink 一旦有值 直接建立ws长连接
    websockLink(val) {
      if (val) {
        this.initWebSocket()
      }
    }
  },
  methods: {
    initWebSocket() {
      this.websock = new WebSocket(this.websockLink)
      this.websock.onopen = this.websocketonopen
      this.websock.onerror = this.websocketonerror
      this.websock.onmessage = this.websocketonmessage
      // this.websock.onclose = this.websocketclose
    },
    websocketonopen() {
      console.log('WebSocket连接成功')
    },
    websocketonerror(e) {
      console.log('WebSocket连接发生错误')
      console.log(36,e);
    },
    websocketonmessage(e) {
      const redata=JSON.parse(e.data)
      console.log(redata);
      console.log('WebSocket信息通知')
      console.log(39,e);
    },
    // websocketclose(e) {
    //   console.log('关闭WebSocket连接')
    //   console.log(44,e);
    // }
  },
  created() {
  },
  destroyed() {
    this.websocketclose()
  },
  mounted() {
    this.websockLink = "ws://"+this.path +"/smart-care/chat?"+this.loginId +"_1"
  }
}

\