Vuex & Websockets

折月煮酒 提交于 2019-11-30 07:06:29

I have an electron application that uses Vue and a websocket for information and here is how I set mine up.

I have a store defined that also actually creates and sets up the websocket.

Store.js

const socket = require("socket-library") // Take your pick of socket libs

const mySocket = new socket(...)
mySocket.on("message", message => store.handleMessage(message))
...other handlers...

const store = {
    handleMessage(message){
        // do things with the message
    }
}

export default store

Renderer.js

import store from "./store"

new Vue({
    data:{
        store
    }
})

This exposes my store at the root level of my Vue and allows me to pass data to components, or what have you. The store manages all the incoming information from the websocket.

With you wanting to use Vuex, you could do essentially the same thing, where Vuex would be your store and when messages come in over the socket, you just pass them to Vuex.

mySocket.on("message", msg => vuexStore.dispatch("onSocketMessage", msg))

and set up your Vue and components to work with Vuex as you typically would.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!