【问题标题】:create socket instance from vuex从 vuex 创建套接字实例
【发布时间】:2020-01-20 06:17:22
【问题描述】:

我正在使用 vue socket io 从套接字获取数据。为了获取数据,我使用像

这样的查询
// ioinstance
import io from 'socket.io-client'
const restaurantId = localStorage.getItem('restaurant-id')
const socketUri = process.env.SOCKET_URI

export default io(socketUri, {
  transports: ['websocket'],
  query: `channel_id=restaurant-${restaurantId}`,
  reconnect: true,
  reconnectionDelay: 500,
  reconnectionDelayMax: 1000,
  pingInterval: 200

})

这里我在成功登录面板后得到 restaurantId 并在成功登录后发送 action 就像

// from vuex module
import VueSocketio from 'vue-socket.io-extended'
import ioInstance from '../../socket-instance'
...
...
socketInitialize ({dispatch}) {
    let restaurantId = await localStorage.getItem('restaurant-id')
    if (restaurantId && restaurantId != null) {
      Vue.use(VueSocketio, ioInstance)
      this._vm.$socket.on(`restaurant-${restaurantId}`, (data) => {
        dispatch('socketIncoming', data)
      })
    }
  }

但是创建 vue 实例不能从 socketInitialize 操作 尽管从 vue 组件创建实例工作正常

// from component
import Vue from 'vue'
import VueSocketio from 'vue-socket.io'
import ioInstance from './socket-instance'
...
...
mounted () {
let restaurantId = await localStorage.getItem('restaurant-id')
if (restaurantId && restaurantId != null) {
    Vue.use(VueSocketio, ioInstance)
    this.$socket.on(`restaurant-${restaurantId}`, (data) => {
    this.$store.dispatch('socketIncoming', data)
    })
  }
}

由于我必须为 socket 实例传递 restaurantId,我没有从 main.js 文件中初始化它(它首先呈现,如果未登录,则 restaurantId 在此处不可用)文件。我需要一些建议,我如何在登录后创建此初始化以及使用 Vue.use 或 this._vm 或 (new Vue()) 或 Vue.prototype 进行初始化的任何替代方式

【问题讨论】:

    标签: sockets vue.js vuejs2 socket.io vuex


    【解决方案1】:

    来自Vue.use(plugin)

    这个方法必须在调用new Vue()之前调用

    所以你必须先注册插件,然后在你准备好之后打开连接。这个问题已经在vue-socket.io-extendedHow to prevent connection until authed?的常见问题部分得到解答。

    基本上你必须通过将autoConnect 设置为false 来告诉socket.io 在实例化时不要打开连接:

    const socket = io({
      autoConnect: false
    })
    

    然后当你准备好调用 open 函数时:

    this.$socket.io.opts.query = `channel_id=restaurant-${restaurantId}`
    this.$socket.open()
    

    【讨论】:

      猜你喜欢
      • 2018-08-03
      • 1970-01-01
      • 2015-07-18
      • 2020-10-22
      • 1970-01-01
      • 1970-01-01
      • 2010-12-12
      • 1970-01-01
      • 2011-10-30
      相关资源
      最近更新 更多