Unlocking the power of a Vuex getter through Vue router

My index.js file holds my routes, and I'm attempting to establish a beforeEnter guard for the admin panel route to only permit authenticated admins. However, when I check

console.log(store.getters.isLoggedIn)
, the output is:

ƒ isLoggedIn(state) {
    return state.user.token ? true : false
}

rather than true or false. I'm uncertain as to why this is occurring. My getter function is defined as:

getters: {
    isLoggedIn: state => {
        return state.user.token ? true : false
    }
}

and here are my routes:

import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import AdminPanel from '../views/AdminPanel.vue'
import store from "../store/authentication.js";

Vue.use(VueRouter)

const routes = [
    {
        path: '/',
        name: 'home',
        component: Home
    },
    {
        path: "/admin",
        component: AdminPanel,
        beforeEnter: (to, from, next) => {
            console.log(store.getters.isLoggedIn)
        }
    }
]

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
})

export default router

The contents of my store.js file:

import Vue from 'vue'
import Vuex from 'vuex'
import authentication from './authentication'
import cart from './cart'

Vue.use(Vuex)

const store = new Vuex.Store({
    modules: {
        authentication,
        cart
    }
})

export default store

In authentication.js:

const authentication = {
    state: {
        user: null
    },
    getters: {
        isLoggedIn: state => {
            return state.user.token ? true : false
        }
    }
}

export default authentication

Answer №1

To begin, import the primary store rather than directly importing a Vuex module:

import mainStore from "../store/index.js";

Your module lacks namespacing, so you can now access the getter like this:

mainStore.getters.isLoggedIn

If it were namespaced, you would have to use namespaced module syntax similar to this:

mainStore.getters['authentication/isLoggedIn']

In this scenario, the first part of the string represents the module name, followed by a slash, and then the getter name.

By not using namespacing, there is a risk of multiple modules utilizing getters with identical names, leading to confusion about the source of the getter.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to guide users to different pages on the website without disrupting the socket connection?

I am looking to create a user-friendly web application utilizing socket.io and express. This website will consist of two main pages: the "Rooms" page and the individual "Room" page. The "Rooms" page allows users to input their name, create a new room, or j ...

Apply the active class to the initial element within the dynamically generated tabs

Using jQuery, I have created these dynamic tabs. My approach involves selecting the first element, nav + tab content. HTML <div class="col-lg-12"> <div class="tabs-container"> <ul class="nav nav-tabs sys ...

Tips for organizing an array of objects that contain null properties

Here is an array that I need help with: "data": { "risks": [ { "id": "22", "name": true, "surname": 0.5, "age": 0.75, "heigth" ...

Using Vue.js: Passing an object from data() to a mounted() function

I'm facing an issue while attempting to pass the grid array to the createGridChart. An error message stating "grid is not defined" keeps popping up: “grid is not defined”. export default { data() { return { grid: [], } ...

A guide to resolving cross-origin resource sharing issues using a reverse proxy

After creating a JavaScript web application for processing documents, I am now looking to integrate with web services like NLTK-server, TIKA-server, and SOLR for further analysis. While I can successfully access the REST endpoints of these services using c ...

Determine whether an element is currently focused using a Vue.js directive

I'm attempting to verify if an element is currently in focus, specifically an input field, and then apply a class to another element. This is the code I have been working on, but for some reason the hasFocus() function isn't functioning as expect ...

Saving Backbone.js Collection as Text File on HDD & Re-importing Data

After experimenting with Backbone.js for a while, I've relied on localStorage to store most of my app data. However, I now want to explore the possibility of exporting my collection to plain text for easy backup purposes. Essentially, I envision a fea ...

The Next.js Link feature does not always guarantee that the component will render correctly, and the serverSideProps function may not always receive updated

Having an issue with next.js - when a user tries to navigate from one profile to another using the Link in the navbar: <li> <Link href={`/profile/${user.user.id}`}> <a className="flex flex-row items-center"> ...

Issue with displaying the scrollbar in Tailwindcss

<div className="col-span-3 h-screen overflow-y-scroll "> <ul className="m-5"> <li className="flex items-center mb-4"> <FontAwesomeIcon icon={faRss} classNa ...

The JSON property is not defined

After making an AJAX call to retrieve data, I receive a JSON Object instead of a string. When I log the object, all its properties appear correctly. However, when attempting to log one specific property, it shows up as undefined. Here is a snapshot of my ...

What is the best way to redirect nodejs requests to a separate nodejs application?

Hello! I am currently working on a project to create an API gateway using Node.js and Express. The goal is to showcase a small-scale microservices architecture by routing requests to different microservices. For instance, if I have microservices A, B, and ...

How to Handle Nested JSON Objects in Node.js

Struggling to send a nested JSON object to my node.js server. This is the expected structure of the JSON object: { "name" : "Plan 1", "schedule": [ { "start": 0, "days": [ { "t ...

What is the most efficient way to utilize a single Google Data Studio template across multiple accounts in a dynamic manner

I've been exploring different options on how to accomplish this: My dataset contains information on various clients, and I am interested in designing a custom Google Data Studio template for specific reports. Ideally, I would like the template to be ...

What is the best way to transfer a JavaScript variable through a query string from one HTML page to another?

Is there a way to pass a JavaScript variable called username from one HTML page, example1.html, to another HTML page, example2.html, using query strings? <script type="text/javascript" > $(document).ready(function() { $('#SubmitForm ...

What is a callback function tied to a specific URL?

I need to implement a functionality in my web application where users can click on a link within a datatable, which will then load a new table on a separate page. This new table should only display rows that have the same id as the row that was clicked on ...

Tips for confirming a website URL using jquery

Looking for help with this form issue: Trying to identify if a valid web address is entered in the input field <form onsubmit='return formValidation()'> <p id="p4"></p> <label>Address:</label> ...

Navigating through an array in Pug

I'm currently extracting data from an external API in JSON format and sending it to my view. The main issue I'm facing is that one of the properties within the Object consists of an Array of Objects. Using the Pug Documentation for iteration, I&a ...

Utilizing Google Maps API to automatically set an address on page load

As a beginner in using the Google Maps API, I have successfully integrated a Google Map into my project. However, I am struggling to figure out how to set specific addresses on the map. I have a list of 2,000 entries in a database, each including an addres ...

What is the best way to call the app.js function from an HTML page in an Express.js environment

Is there a way to trigger the function init() { // } located in app.js from an HTML page? <a href='javascript:init();'> Trigger init </a> The issue with the code above is that it searches for function init() only on the client side ...

Guide on structuring Vue so that all pages have a consistent header and navigation, while still allowing for standalone pages like a registration form

Currently, my Vue app is structured like this: https://i.stack.imgur.com/bMqxX.png In this layout, the login Vue is live under VContent. Certain parts of the header and nav are disabled based on the authentication state. For instance, the logout button i ...