我有一个事件总线,它会将socket.io对象从主实例传递回组件,在那里我需要一些信息,比如套接字id。在我创建的相关事件发出后,在组件上,当收到应答时,我会得到socket对象,但我不知道为什么,我不能在组件中使用它的属性。有什么办法解决这个问题吗?
主vue实例
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)
})
}
})组件文件
<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>发布于 2020-05-09 20:49:45
您的套接字尚未连接,并且还没有id。
您应该等待套接字上的connect事件,然后触发EventBus事件。
mounted() {
console.log('mounted');
EventBus.$on('open-connection', (data) => {
console.log('connected');
socket.on('connect', () => {
EventBus.$emit('connected', socket)
});
socket.open()
})
}https://stackoverflow.com/questions/61696352
复制相似问题