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里面导入

// baseUrl为请求的基本路径
axios.get("/env.json").then(res => {
    if (res.statusText == "OK" && res.data.socket_io_port) {
      localStorage.setItem("socketPort", res.data.socket_io_port);
      Vue.prototype.socketApi = baseUrl + ":" + res.data.socket_io_port;
      Vue.use(
        new VueSocketIO({
          connection: baseUrl + ":" + res.data.socket_io_port
        })
      );
    }
  });

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()
原文地址:https://www.cnblogs.com/wu-hen/p/13246084.html