在vuejs框架中使用websocket , 可以比較方便的運用到vuejs框架的響應式系統 , 以及一些簡單的生命周期函數
var app=new Vue({ el: '#app', data: { server:"ws://127.0.0.1:8080/chat_server", socket:null, }, methods: { //初始化websocket initConn() { let socket = new ReconnectingWebSocket(this.server);//創建Socket實例 this.socket = socket this.socket.onmessage = this.OnMessage; this.socket.onopen = this.OnOpen; }, OnOpen() { let mes = {} mes.type = "test"; this.socket.send(JSON.stringify(mes)); }, OnMessage(e) { const redata = JSON.parse(e.data); console.log(redata) }, }, created: function () { this.initConn(); } })
其他的websocket回調函數可以在initConn中進行賦值給method中的方法
另外websocket是使用的這個類庫reconnecting-websocket , 可以進行自動的斷線重連
<script src="https://cdn.bootcss.com/reconnecting-websocket/1.0.0/reconnecting-websocket.min.js"></script>