Vue-全局websocket 实现消息推送

新建global.js文件

export default {
    ws: {},
    setWs: function(newWs) {
        this.ws = newWs
    }
}

一:main.js 文件中增加

import globalWebSocket from ./js/global.js
Vue.prototype.$globalWebSocket = globalWebSocket

二:app.vue中添加

created() {
    this.initWebSocket();
  },
  methods:{
    //app.vue
    initWebSocket() {
      let that = this;
      if ("WebSocket" in window) {
        console.log("您的浏览器支持 WebSocket!");
        that.ws = new WebSocket(`ws://192.168.1.26:8082/api/websocket`);
        that.$globalWebSocket.setWs(that.ws);
        // that.ws.onopen = that.onopen();
        that.ws.onopen = function() {console.log(webSocket connect successful)};
        that.ws.onclose = function() {
          // 关闭 websocket
          console.log("webSocket connect closed");
          setTimeout(() => {
            that.initWebSocket();
          }, 2000);
        };
      } else {
        // 浏览器不支持 WebSocket
        console.log("您的浏览器不支持 WebSocket!");
      }
    },

三:需使用的页面,保留getMessage方法,只需添加handleMsg方法,将getMessage方法作为接收数据方法,并在mounted函数中加载hanleMsg即可

<template>
	<div>
	<div id="chart" style="width: 700px; height: 200px;"></div>
	</div>
</template>
 
<script>
	export default{
		name:"chart",
		data(){
			return{
				yAxis:[],
				xAxis:[],
			}
		},
		mounted() {
			this.chart();
			this.handleMsg();
		},
		methods:{
         handleMsg() {
            this.$globalWebSocket.ws.onmessage = this.getMessage
         },
        //接收服务器发来的消息
         getMessage: function (e) {
            console.log(e.data);
            this.xAxis = JSON.parse(e.data).xAxis;
            this.yAxis = JSON.parse(e.data).yAxis;
            this.chart();
          },
      
          chart(){
         //有的话就获取已有echarts实例的DOM节点。
      var mychart = this.$echarts.getInstanceByDom(document.getElementById(timechart)); 
             if (mychart == null) { // 如果不存在,就进行初始化。
                 mychart = this.$echarts.init(document.getElementById(chart));
             }
        var option = {
          title: {
            text: 时间(ms)/阶段
          },
          tooltip: {
            trigger: axis
          },
          legend: {
            // data: [Email, Union Ads, Video Ads, Direct, Search Engine]
          },
          grid: {
            left: 3%,
            right: 4%,
            bottom: 3%,
            containLabel: true
          },
          toolbox: {
            feature: {
              saveAsImage: {}
            }
          },
          xAxis: {
            type: category,
            boundaryGap: false,
            data: this.xAxis
          },
          yAxis: {
            type: value
          },
          series: [
            {
              type: line,
              stack: Total,
              data: this.yAxis
            }
          ]
        };
        mychart.setOption(option);
      }
    
	}
</script>
 
<style>
</style>

如果你恰好需要读到这篇文章,希望对你有帮助。如有写的不对或不够好的地方,欢迎指正。

经验分享 程序员 微信小程序 职场和发展