zoukankan      html  css  js  c++  java
  • 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()
  • 相关阅读:
    QT下载速度慢的解决方法
    第七章 多态
    第六章 重复运用class
    第五章 隐藏实现细节
    代码改变世界
    第四章 初始化和清理
    第三章 控制程序流程
    module.exports和exports
    如何与外部源交互
    实现POST服务器
  • 原文地址:https://www.cnblogs.com/wu-hen/p/13246084.html
Copyright © 2011-2022 走看看