Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call Vuex Getters from another javascript file

In /store/user/getters.js:

function getLoggedIn (state) {
  return state.loggedIn
}

In another file: router-auth.js, I try to get the getters.getLoggedIn's value (true or false) like this:

import user from '../store/user'
const loggedIn = user.getters.getLoggedIn
console.log(user.getters.getLoggedIn)

Oddly, it returns the source code of the function instead of the state's value! When I print the log of user.getters, it does list the functions.

like image 692
XPL Avatar asked Sep 16 '26 01:09

XPL


1 Answers

You need to access the instance of the store.

const myStore = new Vuex.store({...});

Here myStore is the instance.

Assuming your store looks something like

store.js

import Vue from "vue";
import Vuex from "vuex";
import user from "./user";

Vue.use(Vuex);

const store = new Vuex.Store({
  modules: {
    user
  }
});

export default store;

You can access the instance by importing store from store.js.

router-auth.js

import store from './store.js';

function someAuthFunction() {
    console.log(store.getters.getLoggedIn);
}

A simple demo on CodeSandbox

like image 108
Steven B. Avatar answered Sep 18 '26 14:09

Steven B.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!