简体   繁体   中英

Passing an object reference to a vuejs component

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.

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 , ie 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM