One: define websocket.js
export default {
ws: {},setWs: function(newWs) {
this.ws = newWs
}
}
Copy the code
Two: import in main.js
import websocket from './utils/websocket'
Vue.prototype.$websocket = websocket
Copy the code
Three: Start in app. vue
1. Define the startup method localSocket
localSocket() {
let that = this;
if ("WebSocket" in window) {
console.log("Your browser supports WebSocket!");
that.ws = new WebSocket('ws:// Back-end address');
that.$websocket.setWs(that.ws);
that.ws.onopen = function() {
console.log('Start connection')
that.$websocket.ws.send('Give the backend the necessary parameters')}; that.ws.onclose =function() {
// Prevent connection timeout, (websocket will be disconnected if there is no data interaction within a certain period of time), shut down and restart
console.log("Connection closed...");
setTimeout(() = > {
that.localSocket();
}, 2000);
};
} else {
// Browsers do not support WebSocket
console.log("Your browser does not support WebSocket!"); }}Copy the code
2. Use it in hook functions
created() {
//websocket
this.localSocket()
},
Copy the code
Accept messages on another page
this.$websocket.ws.onmessage = function(res) {
console.log("Received server content", res);
};
Copy the code