victorsferreira / vue-session

A simplistic session plugin for VueJS backed by SessionStorage and LocalStorage
203 stars 42 forks source link

Can I access to 'this.$session' on Vuex store? #14

Open kotehector opened 6 years ago

mbana commented 6 years ago

Same question here...

gamcoh commented 6 years ago

same question

Pyronerd62 commented 6 years ago

Ok I figured it out. Here we go. In main.js

import VueSession from 'vue-session'
Vue.use(VueSession, {persist: true})

In Store.js or store/index.js

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

let store =  new Vuex.Store({
    state: {
        isLoggedIn: false,
    },
    getters: {
        isLoggedIn:function(state){
            return state.isLoggedIn;
        },
        user:function(state){
            // console.log(store);
            return store._vm.$session.get('user');
        }
    },
    mutations: {
        saveUser(state,payload){
            console.log('user payload', payload);
            // this._vm.$session.start();
            store._vm.$session.set('user',payload);
            state.isLoggedIn = (payload != null)
        }
    },
    actions: {

    }
});

export default store
mbana commented 6 years ago

The point is to avoid having to write such logic. In reply to: https://github.com/victorsferreira/vue-session/issues/14#issuecomment-402272269.

Pyronerd62 commented 6 years ago

I'm not sure what you're asking. That is your basic Vuex store setup. How else do you want to use the mutations and getters? This works for us as the session is tied to the Vue instance itself and it persists across tabs and components.

shlomiLan commented 4 years ago

I managed to access it with Vue.prototype.$session, not sure if this is the "right" way to do it.

aswzen commented 4 years ago
import Vue from 'vue';
import Vuex from 'vuex';
import VueSession from 'vue-session';

Vue.use(Vuex);
Vue.use(VueSession);

export const store = new Vuex.Store({
    state: {
       isLoggedInSession: !!Vue.prototype.$session.get('access-token')
    }
});
abdulmalikgh commented 3 years ago

You can only use this.$session.get() or any method on VueSessionStorage when you are in Vue components. But in other files use the following. First make it global in main.js by import VueSessionStorage from 'vue-session' Vue.use(VueSessionStorage) then in your API or Vuex file

import Vue from 'vue' import VueSessionStorage from 'vue-session'

Vue.prototype.$session.get("token")