vue使用vue-socket.io实现长链接

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()

 

posted @ 2020-07-05 15:04  无痕-范特西  阅读(4018)  评论(1编辑  收藏  举报