美文网首页
2021-04-15 vue和websocket交互

2021-04-15 vue和websocket交互

作者: jinya2437 | 来源:发表于2021-04-15 11:29 被阅读0次
<template>
  <el-dialog :visible.sync="visible" append-to-body @close='closeDialogFn'>
  </el-dialog>
</template>
<script>
import {printApi} from '@/maps/api'

export default{
  data(){
    return{
      websocket: null,
    }
  },
  methods:{
    open(){
      this.visible=true
      // 启动服务器建立连接后,发起请求数据接口 调用该函数websocketonmessage
      this.initwebsocket()
    },
    async getData() {
      let {data,code,message} = await printApi.generatePage()
    },
    closeDialogFn(){
      this.websocket.close() //断开websocket连接
    },
    initwebsocket(){ //初始化weosocket
      const wsuri = `wss:${process.env.VUE_APP_WEBSOCKET_API}/api/websocket/${this.$store.getters["system/employeeId"]}`
      this.websocket = new WebSocket(wsuri)
      this.websocket.onmessage = this.websocketonmessage
      this.websocket.onopen = this.websocketonopen
      this.websocket.onerror = this.websocketonerror
      this.websocket.onclose = this.websocketclose
    },
    websocketonopen(){ //连接建立之后执行send方法发送数据
      console.log("连接建立之后执行send方法发送数据")
    },
    websocketonerror(){//连接建立失败重连
      this.initwebsocket();
    },
    websocketonmessage(e){ //数据接收
      // 刷新页面
      this.getData()
    },
    websocketsend(Data){//数据发送
      console.log('数据发送');
    },
    websocketclose(e){  //关闭
      console.log('断开连接',e);
    }
  },
}
</script>
<style lang="stylus" scoped>

</style>

相关文章

网友评论

      本文标题:2021-04-15 vue和websocket交互

      本文链接:https://www.haomeiwen.com/subject/eoddlltx.html