一:定义websocket.js
export default {
ws:{},
setWs: function(newWs) {
this.ws = newWs
}
}
二:在main.js中引入
import websocket from './utils/websocket'
Vue.prototype.$websocket = websocket
三:在App.vue中启动
1.定义启动方法 localSocket
localSocket() {
let that = this;
if ("WebSocket" in window) {
console.log("您的浏览器支持 WebSocket!");
that.ws = new WebSocket(`ws://后端地址`);
that.$websocket.setWs(that.ws);
that.ws.onopen = function() {
console.log('开始连接')
that.$websocket.ws.send('给后端必要的参数')
};
that.ws.onclose = function() {
console.log("连接已关闭...");
setTimeout(() => {
that.localSocket();
}, 2000);
};
} else {
console.log("您的浏览器不支持 WebSocket!");
}
}
2.在钩子函数中使用
created() {
this.localSocket()
},
四.在别的页面中接受消息
this.$websocket.ws.onmessage = function(res) {
console.log("收到服务器内容", res);
};