vue中使用socket.io

安装

 npm install vue-socket.io

使用,在app.js中注册

 import VueSocketio from 'vue-socket.io';
 Vue.use(VueSocketio, 'http://socketserver.com:1923');

在组件中使用

export default{
  data(){
      return{
          id:''
      }
  }
  sockets:{
    // 通信的name
    //这里是监听connect事件
    connect: function(){
      this.id=this.$socket.id
    },
    customEmit: function(val){
      console.log('this method was fired by the socket server. eg: io.emit("customEmit", data)')
    }
  },
  methods: {
    clickButton: function(val){
        // $socket is socket.io-client instance
        this.$socket.emit('emit_method', val);
    }
  }
}

问题

  • 这里会出现一个问题
    当前页不是直接打开而是通过其它页面router进来的则id无法赋值
    另外如果在mounted中取socket id时如下
export default{
  data(){
      return{
          id:''
      }
  }
  sockets:{
    connect: function(){  //这里是监听connect事件
    },
    customEmit: function(val){
      console.log('this method was fired by the socket server. eg: io.emit("customEmit", data)')
    }
  },
  mounted(){
      this.id=this.$socket.id
  }
  methods: {
    clickButton: function(val){
        // $socket is socket.io-client instance
        this.$socket.emit('emit_method', val);
    }
  }
}

  • 解决问题:则通过路由由其它页面进来时this.id会有值 但当当前页面为初始页面时this.id会为undefined 因为mounted在sockets前面进行
export default{
  data(){
      return{
          id:''
      }
  }
  sockets:{
    connect: function(){  //这里是监听connect事件
      this.id=this.$socket.id
    },
    customEmit: function(val){
      console.log('this method was fired by the socket server. eg: io.emit("customEmit", data)')
    }
  },
  mounted(){
      this.$socket.emit('connect', val); //在这里触发connect事件
  }
  methods: {
    clickButton: function(val){
        // $socket is socket.io-client instance
        this.$socket.emit('emit_method', val);
    }
  }
}
  • 因为通过路由进当前页面sockets里的connect未被触发所以需在mounted里触发一次

你可能感兴趣的:(vue中使用socket.io)