Vue中 引入使用 vue-socket.io

8,823 阅读1分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第7天,点击查看活动详情

传送门:Vue中 使用 WebSocket

1. 安装及引入

vue-socket.io 其实是在 socket.io-client(在浏览器和服务器之间实现实时、双向和基于事件的通信) 基础上做了一层封装,将 $socket 挂载到 vue 实例上,同时可使用 sockets 对象轻松实现组件化的事件监听,在 vue 项目中使用起来更方便。

安装:

vue-socket.io npm地址

npm i vue-socket.io

引入:

// main.js
import Vue from 'vue'
import store from './store'
import App from './App.vue'
import VueSocketIO from 'vue-socket.io'

Vue.use(
  new VueSocketIO({
    // 生产环境建议关闭,开发环境打开(在控制台看到socket连接和事件监听的信息)
    debug: true, 
    connection:'http://metinseylan.com:1992',
    options:{
      // 创建时是否自动连接 我们这里设定为false,在指定页面再开启
      autoConnect: false,
      // 路径(默认值:/socket.io/) 
      path: "/my-app/",
      // 目前有两种传输方式:HTTP long-polling(可简称:polling)、WebSocket
      transports: ['polling'],
      // 附加请求头(在服务器端的 socket.handshake.headers 对象中找到)
      extraHeaders:{},
    },
    // 如果没有使用到 store 可不写
    vuex: {
      store,
      actionPrefix: 'SOCKET_',// vuex action 前缀
      mutationPrefix: 'SOCKET_', // vuex mutation 前缀
    },
  })
)

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')
参数类型默认值是否必选描述
debugBooleanfalse可选择为调试启用日志记录
connectionString / Socket.io-clientnull必要Websocket 服务器 url 或 socket.io-client 实例
vuex.storeVuexnull可选择Vuex store 实例
vuex.actionPrefixStringnull可选择发出服务器端 vuex 操作的前缀
vuex.mutationPrefixStringnull可选择发出服务器端 vuex 突变的前缀

更多参数配置可参考:Socket.IO 官方文档

2. 组件内使用

<template>
  <div class="wrap">
    <button @click="socketEmit">连接Socket</button>
    <button @click="socketSendmsg">发送数据</button>
  </div>
</template>

<script>
export default {
  data(){
    return {
      randomId:null,
    }
  },
  methods:{
    socketEmit(){
      // 开始连接 socket
      this.$socket.open();
      // 订阅事件,testCall 是与后端约定好的名称
      this.sockets.subscribe('testCall', (res) => {
        if(res.code == 200 && res.randomId === this.randomId){
          console.log('召唤成功')

        }
      })
    },
    // 发送消息
    socketSendmsg(){
      this.randomId = Math.random();
      // testCall 是与后端约定好的名称
      this.$socket.emit('testCall', { 
        "randomId": this.randomId,
        "deviceId": "123456"
      });
    },
  },
  sockets: {
    connect: function () {
      console.log('连接成功')
    },
    disconnect: function () {
      console.log('断开连接')
    },
    reconnect: function () {
      console.log('重新连接')
    },
  },
  beforeDestroy(){
    // 关闭 Socket
    this.sockets.unsubscribe('testCall'); 
    this.$socket.close();
  },
}
</script>

参考文章:vue-socket.io 使用教程与踩坑记录