nathantsoi / vue-native-websocket

native websocket with vuex integration
943 stars 162 forks source link

Does this work with Vuex? #124

Open wildone opened 4 years ago

wildone commented 4 years ago

I have tried using this with Vuex and it does not work :(

tigerclaw-az commented 4 years ago

Can you post an example of your code to show what isn't working? I've been using this for a year and it works great with Vuex!

hcq11 commented 3 years ago

Can you post an example of your code to show what isn't working? I've been using this for a year and it works great with Vuex!

Store/vuex can not find mutation in sub module ,do you have good solution? thank you very much!

tigerclaw-az commented 3 years ago

Here's a sample from some code I'm using, it was mostly taken straight from the README doc:

import Vue from 'vue';
import router from '@/routes';

import mutationTypes from '@/store/mutation-types';

const state = {
    isConnected: false,
    isOpen: false,
    message: '',
    reconnectError: false,
};

const getters = {
    isConnected: state => {
        return state.isConnected;
    },
};

const actions = {};

const mutations = {
    [mutationTypes.websocket.SOCKET_ONOPEN](state, event) {
        Vue.$log.info(state, event);
        state.isConnected = true;
        state.isOpen = true;
    },
    [mutationTypes.websocket.SOCKET_ONCLOSE](state, event) {
        Vue.$log.info(state, event);

        if (router.currentRoute.path !== '/offline') {
            router.push('/offline');
        }

        state.isConnected = false;
        state.isOpen = false;
    },
    [mutationTypes.websocket.SOCKET_ONERROR](state, event) {
        if (state.isOpen) {
            // Only display error if the error wasn't from socket close
            Vue.$log.error(state, event);
        }

        if (router.currentRoute.path !== '/offline') {
            router.push('/offline');
        }
    },
    [mutationTypes.websocket.SOCKET_ONMESSAGE](state, message) {
        Vue.$log.debug(state, message);
        state.message = message;
    },
    // mutations for reconnect methods
    [mutationTypes.websocket.SOCKET_RECONNECT](state, count) {
        Vue.$log.info(state, count);
    },
    // mutations for reconnect methods
    [mutationTypes.websocket.SOCKET_RECONNECT_ERROR](state, count) {
        Vue.$log.error(state, count);
    },
};

export default {
    // Can't use namespace until Issue is fixed: https://github.com/nathantsoi/vue-native-websocket/issues/40
    // namespaced: true,
    modules: {
        // Add any modules (if using modules for your Store)
    },
    state,
    getters,
    actions,
    mutations,
};