vue定义全局websocket

1.首先创建一个全局 js 文件,如 global.js ,用于定义全局变量 ws 和方法 setWs()

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

在 main.js 中引入 global.js

// main.js
import global from './xx/global.js'
Vue.prototype.$global = global

在 app.vue 中初始化 webSocket ,并在 created() 方法中调用

//app.vue
<template>
  <div id="app">
    <router-view></router-view>
  </div>
</template>

<script>
  export default {
    name: 'App',
    created() {
      this.localSocket()
    },
    methods: {
      //app.vue
      localSocket() {
        let that = this
        if ('WebSocket' in window) {
          console.log('您的浏览器支持 WebSocket!')

          that.ws = new WebSocket(`wss://xxxxxx`)
          that.$global.setWs(that.ws)
          that.ws.onopen = function() {
            console.log('开始连接')
          }
          //that.onopen(); 这个地方未定义是会报错,所以我写成了  that.ws.onopen = function() {console.log('开始连接')};

          that.ws.onclose = function() {
            // 关闭 websocket
            console.log('连接已关闭...')
            setTimeout(() => {
              that.localSocket()
            }, 2000)
          }
        } else {
          // 浏览器不支持 WebSocket
          console.log('您的浏览器不支持 WebSocket!')
        }
      },
    },
  }
</script>
<style></style>

在其他页面发送和接收 socket 消息

initWebSocket() {
        //初始化weosocket
        let that = this
        that.$global.ws.send('OK!')
        that.$global.ws.onmessage = that.websocketonmessage
      },
      websocketonmessage(e) {
        //数据接收
        this.list.push({ notice: e.data })
        this.badge = this.list.length
      },```

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员阿明

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值