0.2.0 • Published 4 years ago

@szgc/plt-socket v0.2.0

Weekly downloads
-
License
ISC
Repository
-
Last release
4 years ago

@szgc/plt-socket

安装

npm i @szgc/plt-socket -S

初始化

import "@szgc/plt-socket";

使用

平台封装的 socket 实例已注册到 Vue 原型链上的\$socket 属性上,在开发时直接使用即可

/**
 * 注册socket事件
 * @param eventId {string} 事件名
 * @param callback {function} 回调函数,data为socket事件传递的数据
**/
this.$socket.on(
  eventId : string,
  callback: {
    (data : any) : void;
  }
);
/**
 * 卸载已注册socket事件
 * @param {string} eventId 事件名
 * @param {Function} 此前注册的回调函数
**/
this.$socket.off(eventId : string, callback: Function) : void;

举例

export default {
  mounted() {
    this.onMessageReceived = data => {
      // TODO do something
    };
    // 因为使用bind函数会重新产生function实例,在卸载事件时会出问题
    // 所以采用运行时定义的方式进行事件注册
    this.$socket.on("messageReceived", this.onMessageReceived);
  },
  destroyed() {
    this.$socket.off("messageReceived", this.onMessageReceived);
  }
};