美文网首页前端技术
Vue 中使用 socket.io

Vue 中使用 socket.io

作者: 时间走了光 | 来源:发表于2019-05-09 18:17 被阅读0次

1、安装相应的依赖包

npm install vue-socket.io --save
npm install socket.io-client --save

2、main.js中引入

import SocketIO from 'socket.io-client';
import VueSocketIO from 'vue-socket.io';
Vue.use(new VueSocketIO({
  debug: true,
  connection: SocketIO('http://114.116.99.13:9092') //xxx填后台给的socket地址,端口号根据实际后台端口写
}));

3、再组件中使用

sockets: {
    disconnect () {
        console.log('socket 断开连接了!'); // 监听socket断开
    },
    connect () {
       // 监听socket连接
        console.log('socket 已经连接了!');
       // 给后台的user_info这个方法传递参数并输出回调信息
       this.$socket.emit('user_info', this.loginUserInfo.userId, (data) => {
           console.log('执行回调数据:', data);
       });
    },
    // 监听后台事件,方法是后台定义和提供
    msg_info (data) {
      console.log('执行服务端方法---------------');
    },
},
mounted () {
  this.$socket.emit('connect'); // 此处需要再调用一次connect方法;
}

相关文章

网友评论

    本文标题:Vue 中使用 socket.io

    本文链接:https://www.haomeiwen.com/subject/zhegoqtx.html