1.下載
npm install vue-socket.io --save
2.在main.js中引入
import VueSocketIO from "vue-socket.io";
import SocketIO from "socket.io-client";
Vue.prototype.SocketIO = SocketIO;
3.獲取鏈接地址並在main.js里面導入
const baseSocket = 'http://8.8.8.8:8080'
Vue.prototype.socketApi = baseSocket
Vue.use(new VueSocketio({ debug: true, connection: SocketIO.connect(baseSocket, { path: '', transports: ['websocket', 'xhr-polling', 'jsonp-polling'], }) }));
4.在組件中使用
this.socket = this.SocketIO(this.socketApi); this.socket.on("connect", datas => { this.socket.emit("login", this.info.id); this.socket.on("daymarket", data => { console.log(data) }); }); //其中socket 可以在data里面定義 //connect和login和daymarket都是后台定義的名字,this.info.id根據后台要求傳的id
5.銷毀
this.socket.disconnect()
