Utilizing VueJs (Quasar) to access vuex store within the router

Recently, I have been diving into learning Vuex and creating an authentication module. Following a tutorial, I reached a point where I needed to use the store in the router. However, after importing my store at the top of the router index.js file, I noticed that I couldn't access getters as they were showing up as undefined.

The strange thing is that the store works perfectly fine in Vue components. So, why am I facing this issue? Could it be because the store is not properly initialized when the router is created? The tutorial I followed didn't mention any problems like this.

This is how my router/index.js looks:

import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes'
import store from '../store'

Vue.use(VueRouter)

export default function() {
  const Router = new VueRouter({
    scrollBehavior: () => ({ x: 0, y: 0 }),
    routes,
    mode: process.env.VUE_ROUTER_MODE,
    base: process.env.VUE_ROUTER_BASE,
  })

  Router.beforeEach((to, from, next) => {
    if(to.matched.some(record => record.meta.requiresAuth)) {
      if (store.getters.isLoggedIn) {
        next()
        return
      }
      next('/login')
    } else {
      next()
    }
  })
  
  return Router
}

And here's my store/index.js:

import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import getters from './getters'
import mutations from './mutations'
import actions from './actions'

Vue.use(Vuex)

export default function() {
  const Store = new Vuex.Store({
    modules: {},
    namespaced: true,
    getters,
    mutations,
    actions,
    state,
    strict: process.env.DEV,
  })

  return Store
}

Answer №1

No need to make changes to your default Quasar store/index.js file

Simply utilize it as a Promise function:

import store from '../store'
....
if (store().getters['auth/isLoggedIn']) {
   next()
   return
}

Answer №2

After facing a challenge with my store's export default settings, I took matters into my own hands and made some modifications that successfully resolved the issue.

Here is the revised code snippet that now works perfectly:

const customStore = new Vuex.Store({
  modules: {
   authentication
  },
  namespaced: true,
  strict: process.env.DEV,
})

export default customStore

Answer №3

On the 24th of February, you are now able to...

located at the beginning of router.js

import { useStore } from 'vuex'

and within the module function thereafter

const store = useStore()

You will then be able to access store.state and perform actions like

store.commit('ANY_MUTATION',data)
etc,etc

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

The Angular application must remain logged in until it is closed in the browser

Currently, my Angular app includes authentication functionality that is working smoothly. The only issue is that the application/session/token expires when there is no user activity and the app remains open in the browser. I am looking for a solution wher ...

Tips for resolving the issue: SyntaxError - Unexpected token import

I've encountered this error in the past and have looked at other solutions, but none of them seem to work for my specific issue. My package.json file includes the following dependencies: "dependencies": { "axios": "^0.15.2", "babel": "^6.5. ...

Struggling with this mixed content problem

Encountering a problem while loading a js file: https://code.jquery.com/jquery-1.11.1.min.js, which is being loaded on my webpage in this manner: <script src="https://code.jquery.com/jquery-1.11.1.min.js"></script> Upon loading my webpage, an ...

Eliminate the array from the data retrieved through an http request in AngularJS

Currently, I am making an http call to retrieve data from a database. This process involves calling 6 different types individually. $scope.getAll = function() { var url = 'http://someurl/'; var allObjects = []; $sc ...

What is the best way to incorporate auto-suggestion functionality into a search field using Vue.js without relying on Vue

My current setup looks like this: <div id="app"> <h1>Basic example of typeahead functionality</h1> <input placeholder="Search countries" @input="searchInput" v-model="typeaheadData" /> <ul v-if="!selectedCountry & ...

Node.js encountering req.body as undefined when using form-data as the content-type

After creating a small demonstration for this form-data passing API, I attempted to test it using Postman. However, I encountered an issue where no data was being retrieved. Code const http = require("http"); const express = require("expres ...

Dynamic content for tooltips in Angular

Currently, I am facing a challenge where I need to dynamically populate content in a tooltip by executing a function with a parameter. This parameter holds the crucial information required to update the tooltip content. The complexity arises from the fact ...

Saving the index.html file to disk when the button is clicked

Is there a way to export the current HTML page to a file? I have attempted to achieve this using the following code, but it only works when the page is loaded and not with a button click. <?php // Start buffering // ob_start(); ?> <?php file_pu ...

Safari has trouble with AJAX cross-origin requests, while Chrome and Firefox handle them without issue

I am developing a Shopify app that utilizes script tags and requires an ajax call to our server to retrieve necessary information about the shop. While everything seemed to be functioning correctly, my colleague pointed out that it was not working on his i ...

Include the script tags retrieved from an array

I'm exploring the idea of dynamically adding JavaScript to the DOM using an array and a loop. The goal is to load each script sequentially, starting with scripts[0], then scripts[1], and so on. var myScripts = [["external", "https://code.jquery.com/j ...

"Unleashing the power of webpacker gem to tap into your assets

Can someone help me understand how to access assets from webpacker gem within vue.js components? Specifically, I'm trying to create a div with a background image. I've attempted using both the /app/assets/images and /app/javascripts/assets folder ...

Issue with window.location.href and unexpected behavior in Firefox 7

I can't seem to figure out the issue I'm encountering on FF7 My ajax calls are returning a json object (jquery). if(data.result=='ok') { var url = baseURL + "azioni/makeForm/" + data.actcode + "/DIA/" + data.az_id; console.log ...

How can Vue.js be incorporated into a Pug template without relying on a CDN?

For quite some time now, I've been pondering this question: If I were to install Vue JS or another library using npm, how would I go about loading that specific library into a pug template? Is it even possible? ...

Displaying dynamic content in JavaScript using Galleria module

Hello and thank you for taking the time to check out my question. I've encountered a little issue that I can't seem to solve by myself. I'm hoping someone could lend me a hand. On my website, there is a dynamic field filled with a code from ...

Reset input fields while retaining placeholder text

Seeking advice on how to use this handy jQuery tool properly: $('.myDiv input').each(function () { $(this).val(""); }); Though it clears my form, I'm struggling to maintain the placeholders of the inputs. Any suggestions? C ...

The length of JSON data retrieved may vary between Internet Explorer and Firefox

After receiving JSON data from the server via AJAX, I proceeded to evaluate it as follows: request.responseText=[{name:xxx},{name:yyy},{name:zzz}]. I then used the following code snippet: var data=eval(request.responseText); alert(data.length); Surpri ...

References to high order functions in JavaScript

Although the code below is functional, I believe there might be a more efficient approach. I am currently passing a reference to the higher-order function's scope. var self=this; this.nodeModal.find(".modal-footer .save").click(function(){ ...

Tips for sending data from Jade to a Node.js endpoint function

I am unfamiliar with Express and I am trying to figure out how to pass the user's username from a Jade file to an endpoint function in my JavaScript file. Below is the code for the endpoint function in index.js: router.get('/userdetail', fu ...

Tips for utilizing jQuery to identify an image that is being hovered on?

Concept My goal is to create an effect where a user hovers over an image and a transparent overlay div appears on top of it. This overlay div starts with a height of 0px and should increase to half of the image height upon hover. The hover functionality ...

Is the definition of uniforms present in the THREE.js RawShaderMaterial?

The suggested reading regarding THREE.Js RawShaderMaterial states: Default uniforms and attributes are not automatically included in the GLSL shader code. Nevertheless, I have successfully executed the following shader using a rawShaderMaterial: ...