Using Vuex in the router: A comprehensive guide

I am having trouble accessing data from the store in the router.

I have attempted three different methods, but none of them seem to be working correctly.

Here are the methods I tried:

// ReferenceError: store is not defined
console.log(store.state); 

// ReferenceError: $store is not defined
console.log($store.state);

// TypeError: Cannot read property '$store' of undefined
console.log(this.$store.state);

Interestingly, when I try using it in App.vue, it works fine.

This is how I used it in my App.vue file:

export default {
  created() {
    console.log(this.$store.state.user);
  },
}

Can anyone provide some insight on what I might be doing wrong?


Here is a snippet of my store/index.js file:

state: {
  user: {
    loggedIn: false,
    data: null
  },
},

And here is a snippet from my router/inde.js file:

router.beforeEach((to, from, next)=>{
    // console.log(store.state);
    // console.log($store.state);
    console.log(this.$store.state);
   // if(this.$store.state.user.loggedIn){
   // next('/login');
  }else
    next();
})

Answer №1

To get started, import the store by using this code:

import myStore from '../store/';

Next, you can access the store like this:

myStore.state

Don't forget to export it in your store/index.js file as shown below:

export default new Vuex.Store({
     //configuration settings
});

Answer №2

The ability to access the $store in App.vue is made possible by including store.js within your app.js and then adding it to the Vue instance. To utilize your vuex store in a different JavaScript file, all you have to do is import it.

import Store from './store.js';

console.log(Store);

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

I am puzzled by the fact that the data stored in Vue.js Vuex using Firebase is not accessible when reloading the page in

When a user hits the reload button on the web browser, I am unsure of what exactly happens... After logging in for the first time, it is fine to display user data. The store state data and caching data from localStorage are accessible. However, upon reloa ...

Tips for implementing a dynamic value in the ng-style based on certain conditions

Is there a way to set a background-color conditionally using ng-style when the color value can be updated from $scope? These are the variables in my scope: $scope.someone = { id: '1', name: 'John', color: '#42a1cd' }; $scope ...

When utilizing *NgIf, the button will be shown without the accompanying text being displayed

When trying to display either a confirm or cancel button based on a boolean set in my component.ts, I implemented the following code in my HTML: <mat-dialog-actions class="dialog-actions"> <button class="cancel-btn" ...

struggling to update an array with user inputs on my to-do list app

I'm currently in the process of creating a small to-do list with some specific functionality. I want each text input (or a copy of it) to be added to an empty string, ensuring that the original input remains unchanged. The goal is to have a function t ...

The reactivity of arrays in Vue components' props is limited

I've got an array with component data that I'm attempting to render using v-for <div :style="style" class="editor-component" v-for="(component, index) in components"> <Component :is="component.name" v-bind="component.o ...

Looking to preserve the "ALL" selection in a JavaScript-CSS filter?

On the front page, there are approximately 16 posts displayed along with a filter featuring 4 drop-down menus showcasing post categories. I have assigned category names as classes to each post div and am currently using javascript to hide them. The code s ...

What is the best way to implement a multi-row form in Vue.js?

Form Structure: <card-wrapper v-for="(passenger, index) in form.passenger" :key="index" :icon="['fas', 'user']" :title="`Passenger ${index + 1}`" class="mb-5" > <validation-observer ...

Running Javascript code after rendering a HandleBars template in Node/Express

I have a Node.js application where I am trying to load data into a jQuery datatable after the data has been fetched. Currently, I am able to populate the table with the data, but I am facing issues initializing the datatable. Here is how I render the temp ...

What is the best location to store the JWT bearer token?

Exploring options for storing JWT tokens in a Bearer header token for my application. Looking for the most efficient storage mechanism. Would love some insight on how to accomplish this using jQuery. Any recommendations for a secure method? ...

Vuejs Namespaced Mixins

Creating a namespaced mixin is something I am interested in achieving. Let's use the example of a notification mixin: (function() { 'use strict'; window.mixins = window.mixins || {} window.mixins.notification = { met ...

Browsing through a collection of JSON objects with a user interface

I need a way to filter and display a list of Dogs based on a search query. I initially stored the data in an array within the state, but with an increasing number of entries, I've decided to switch to JSON format for better management. However, I&apo ...

Difficulty encountered when attempting to utilize keyup functionality on input-groups that are added dynamically

I've exhausted all available questions on this topic and attempted every solution, but my keyup function remains unresponsive. $(document).ready(function() { $(document).on('keyup', '.pollOption', function() { var empty = ...

Focusing on the active element in Typescript

I am working on a section marked with the class 'concert-landing-synopsis' and I need to add a class to a different element when this section comes into focus during scrolling. Despite exploring various solutions, the focused variable always seem ...

Meteor.js in conjunction with ScrollMagic TweenMax.to

Having trouble getting Meteor template.rendered to work with ScrollMagic I am trying to make this code function properly. if (Meteor.isClient) { Meteor.startup(function () { scrollMagicController = new ScrollMagic(); Template.StartAnimatio ...

"Make sure to always check for the 'hook' before running any tests - if there's an issue, be sure

before(function (func: (...args: any[]) => any) { app = express(); // setting up the environment sandbox = sinon.createSandbox(); // stubbing sandbox.stub(app, "post").callsFake(() => { return Promise.resolve("send a post"); }); ...

Swap out the old nested array for a fresh array

Currently, I am dealing with an array nested inside another array. The structure looks like this: Structure: First Array [ { Second Array [ { } ] } ] I am attempting to replace all instances of Second Array with a new array that I have cr ...

Ensure that the dropdown <select> remains open even while filtering through options

I am currently working on implementing a mobile-friendly "filtered dropdown" design: https://i.sstatic.net/SYjQO.png Usually, a <select> control remains closed until the user clicks to open it. Is there a straightforward way to keep it always open ...

Transferring a JSON object to a PHP script

I am attempting to send a JSON object with a structure like this: {"service": "AAS1", "sizeTypes":[{"id":"20HU", "value":"1.0"},{"id":"40FB","2.5"}]} Just to note: The sizeTypes array contains a total of approximately 58 items. Upon clicking the submit ...

Would it be considered poor design to send back a partial view with just a simple JavaScript alert in my ASP.NET MVC application?

I have a unique Action method that handles exceptions by returning an _error partial view: [AcceptVerbs(HttpVerbs.Post)] public PartialViewResult Register(string id, int classid) { try { Thread.Sleep(3000); User user = r.FindUser(i ...

Creating a column that adjusts dynamically in PDFMAKE

Currently, I am utilizing PdfMake within my VueJS app to generate PDFs. I am curious as to whether it is possible for me to have control over the columns displayed in my template by using the data that is being printed as a variable. I am aiming to achiev ...