vue中使用vue-socket.io

vue-socket.io的使用

参照vue-socket.io的git地址说明文档进行安装

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:{
    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里触发一次

sockets:{
    connect: function(){  //这里是监听connect事件
      this.id=this.$socket.id
    },
    customEmit: function(val){ //这里是监听customEmit事件
      console.log('this method was fired by the socket server. eg: io.emit("customEmit", data)')
    }
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值