简体   繁体   中英

get data of Vue component from outside vue

I use Vue loaded from a script (not a CLI) and i use it in file called admin.js. It stores multiple components that may interact with eachother by emiting events. No Vuex used here. I also have different file called socket that creates a websocket and onmessage event listener. It is worth noting that socket has nothing in common with Vue components and it is different part of app. Vue components may use socket because it is defined as:

var Socket = new WebSocket(wsServer + ":" + wsPort);

Because it is created in main scope all the Vue components may use it like:

Socket.send({ ... })

However there may be some situations that may require analyzing data that came from socket and react to it with data from multiple components.

I see two solutions for these:

  1. add in every component that may wait for data from socket addEventListener and call internal methods of components depending on which command came from socket. In other words - send data from Socket to Components and react properly. That is in my opinion not so good especially because event listeners like to multiply themselves and there is a lot of mess with securing from it.

  2. get data from components directly from socket. In that i mean if particular message appears in event listener onmessage check components for needed data and react.

That would look like this:

Socket.onmessage = function(e) {
    let json = JSON.parse(e.data);
    if ( json.cmd == "CALLDATA" ) {
        // get data from Vue component
        let obj = objectized data from component 
        Socket.send(obj)
    }
}

And here comes the question: How (or is it possible?) to get data from one or more components from outside of Vue Components?

Create a simple plugin to wrap the socket and send/receive messages. When you create the components, install the plugin - Vue.use(MySocketPlugin) - and then in each component it will be available as the name you give it - ie this.$mySocketPlugin .

this.$mySocketPlugin.onmessage('some-message', function (payload) {
     // do the thing with payload
})

this.$mySocketPlugin.send('some-other-message', data)    

Alternatively, create a global mixin with the necessary methods for sending and receiving data. Both approaches are really similar, just a matter of which you prefer.

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