Reputation: 567
I need to pass an object reference to a vue
-component. The background behind this is the following:
I have a webapp, that uses vuejs
only for the chat. However, the webapp already opens a WebSocket
-connection to my server for data messaging. I would like to reuse this existing WebSocket
-connection inside the vue
-powered Chat, instead of opening another parallel connection. I was struggling for some time to pass the WebSocket
object from my webapp to the vue
-component.
I want to pass a reference to a fully dynamic WebSocket
-connection, so props
or state
are no option.
Upvotes: 0
Views: 189
Reputation: 567
It's actually quite easy to pass a reference to an arbitrary object to a vue
-component. Suppose you mount your app as follows:
this.app = new Vue({
render: (h) => h(Chat),
}).$mount("#myChatApp");
Setting the reference on the app
, i.e. this.app = myWebSocket
won't expose the WebSocket
to the Chat component, but only to the global Vue
-instance. Instead you have to access the component through:
this.app.$children[someIndex].ws = myWebSocket;
And voíla: It works! I'm just getting started with vuejs
and amazed how it all boils down to pure js
. Hope this helps somebody who stumbles over a similar problem!
Upvotes: 1