Vue中 引入使用 vue-socket.io

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')

Introduction | 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>


 

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

江湖行骗老中医

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值