A, install,
npm install sockjs-client --save
npm install stompjs --save
Copy the code
Second, the use of
import SockJS from 'sockjs-client'; import Stomp from 'stompjs'; Methods: {// Init parameter initWebSocket(){this.connection(); let self = this; This.timer = setInterval(() => {try {self.stompClient.send('test'); } catch (error) {console.info(" broken :" + error); self.connection(); }}, 5000); }, // Establish connection(){let orderId = '20068765675656565654 '; Establish a connection object / / / / connected to the server to provide communication interface, the connection after can subscribe to broadcast information and personal information. This socket = new SockJS (` ` http://22.0.157.40:10020/business-h5/orders/ws); // Get the client object of the STOMP subprotocol this.stompClient = stomp.over (this.socket); // Set let headers = {}. / / connection to the server by enclosing stompClient. Connect (headers, () = > {/ / subscribe server provides a topic of enclosing stompClient. The subscribe ('/status, (response) => { console.info(response.body); }); }, (err) = > {/ / connection error occurs when the handler console. Info (' failure '); }); }, // Disconnect (){if (this.stompClient! = null) { this.stompClient.disconnect(); console.info("Disconnected"); }}}, beforeDestory(){// Disconnect when the page leaves, clear timer this.disconnect(); clearInterval(this.timer); }Copy the code