首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何访问vue事件全局总线传递的对象属性

如何访问vue事件全局总线传递的对象属性
EN

Stack Overflow用户
提问于 2020-05-09 19:58:28
回答 1查看 79关注 0票数 0

我有一个事件总线,它会将socket.io对象从主实例传递回组件,在那里我需要一些信息,比如套接字id。在我创建的相关事件发出后,在组件上,当收到应答时,我会得到socket对象,但我不知道为什么,我不能在组件中使用它的属性。有什么办法解决这个问题吗?

主vue实例

代码语言:javascript
复制
import Vue from 'vue'
import { EventBus } from './event-bus'
import App from './App'
import router from './router'
import SocketIO from 'socket.io-client'

// Before you create app
//Vue.config.devtools = true;

const socket = SocketIO('https://host-notification.herokuapp.com/', {
  autoConnect: false
});

/* eslint-disable no-new */
new Vue({
  el: '#inbox',
  data: {},
  router,
  render: h => h(App),
  watch: {
    $route(to, from ){
      console.log(to, from);
    }
  },
  created() {
      this.$router.push({ path: 'inbox' });
  },
  mounted() {
    console.log('mounted');
    EventBus.$on('open-connection', (data) => {
      console.log('connected');
      socket.open()
      EventBus.$emit('connected', socket)
    })
  }
})

组件文件

代码语言:javascript
复制
<script>
import { EventBus } from '../../event-bus';

export default {
  data () {
    return {
      socket: null,
      isRegistered: false,
      isConnected: false,
      username: null,
      message: '',
    }
  },
  created() {

  },
  mounted() {
    EventBus.$on('connected', (socket) => {
    //this will log the socket object passed from the main vue instance 
      console.log(socket)
      this.socket = socket;
      this.isConnected = true;
    //this will not log anything and result in an undefined message in console 
      console.log(this.socket.id) 
    })
  },
  methods: {
    connect(){
      if( this.isRegistered === false){
        this.username = this.username;
        this.isRegistered = true;
        EventBus.$emit('open-connection')
        return this.username;
      }
    }
  }
}
</script>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-09 20:49:45

您的套接字尚未连接,并且还没有id。

您应该等待套接字上的connect事件,然后触发EventBus事件。

代码语言:javascript
复制
mounted() {
 console.log('mounted');
 EventBus.$on('open-connection', (data) => {
   console.log('connected');
   socket.on('connect', () => {
      EventBus.$emit('connected', socket)
   });
   socket.open()
  })
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61696352

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档