【发布时间】: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