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
},```