Can I access VueSession in main.js for Vue.js?

In my main.js file, I have set up the following configuration:

import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'
import Home from './views/Home.vue'
import Login from './views/Login.vue'
import Profile from './views/Profile.vue'
import Simulations from './views/Simulations.vue'
import VueSimpleAlert from "vue-simple-alert"
import StatisticPage from './views/StatisticPage.vue'
import VueSession from 'vue-session'
import Users from './views/Users.vue'

Vue.use(VueSimpleAlert)
Vue.use(VueRouter)
Vue.use(VueSession)

Vue.config.productionTip = false

const routes = [
  {path: '/', name:'Login', component: Login },
  {path: '/users', name:'Users', component: Users},
  {path :'/home', name:'Home', component: Home},
  {path: '/subject/:Pid', name: 'Profile', component: Profile},
  {path: '/subject/:Pid/simulations', name:'Simulations', component: Simulations},
  {path: '/subject/:Pid/simulations/:Sid/statistics', name:'Statistics', component: StatisticPage}
]

const router = new VueRouter({
  routes,
  mode: 'history'
})

router.beforeEach((to, from, next) => {
  if(to.name !== 'Login'){
    if(this.$session.get('token')){
      next()
    }else{
      next({ name: 'Login'})
      next()
    }
  }else{
    next()
  }
})

new Vue({
  router,
  render: h => h(App),
}).$mount('#app')

export default router

I am facing an issue where I am unable to access the session information in the router as I keep receiving an error stating that $session is undefined. Can someone guide me on how to properly access the session information within the router?

Answer №1

To access the Vue instance within your router, utilize router.app instead of using this

Replace this line :

this.$session.get('token')

with:

router.app.$session.get('token')

For more information on Router Instance Properties, check out: https://router.vuejs.org/api/#router-instance-properties

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

Looking to construct dynamic checkboxes in Angular by parsing a JSON object retrieved through AJAX

I have a JSON document structured like the example below, and I am looking to generate checkboxes dynamically using Angular. let data = { "Name":[ { "tagId":4489,"name":"Name","label":"Employee Name" } ], "Service":[ { "tagId": ...

Adjustable dimensions for a collection of squares based on screen size

I am currently designing a grid composed of 1:1 squares and allowing the user to continually add more squares. My main goal is to ensure that the size of each square maintains its aspect ratio while being able to resize accordingly. The challenge lies in k ...

What is the method to retrieve a randomly generated class from an id?

Is there a way to target elements that have the class "my_class" within the element with the id of "info_id"? It's important to note that these elements may also have another class, which I'm not interested in selecting. <div id="info_id"> ...

chart for visualizing two rows with matching IDs and dates

I have been attempting to accomplish the following two scenarios: 1) When both ID and dates are the same in the chart, but the descriptions differ, I want to display them on separate lines. 2) If there is not enough room to show the row label, I would li ...

PDF Embed Whitelist

Is there a way to embed PDFs on a specific domain in a read-only format without allowing saving or downloading? While services like Scribd and Slideshare offer private options, I haven't found one that allows whitelisting for embeds on certain domains ...

What are the steps for enlarging the display containing components with the 'position: absolute' style?

How can I magnify the screen with the following code? .drawing-board { width: 25%; height: 25%; background-color: black; position: relative; /* transform: scale(2, 2); */ } .drawing-board .box-1 { width: 20px; height: 20px; background-c ...

CKFinder Error: Unable to find definition for t.event.special.swipe

Upon using CKFinder 3.2.0 with Firefox 44.0, I encountered the following error message. Interestingly, this issue is exclusive to Firefox while Chrome works perfectly fine. Any insights on what could be causing this problem and how it can be resolved? Ty ...

Expanding Drop-Down Feature in CodeIgniter: How to Create Nested Dropdown Menus

I'm working on a dropdown menu that is populated with items using a foreach statement. When an item is selected, I need another dropdown menu to appear where specific items can be specified. First Dropdown - Categories (Completed) When a Category is ...

Unraveling the mysteries of JQGrid column sizing characteristics

My tree grid is causing me some headaches with its columns all having specified widths. The headers and columns below are completely out of sync, even when the data in them is short. In particular, when a column heading title is shorter than the width of ...

Ways to conceal and reveal image and text elements based on array loop output

I am currently working on setting up a questionnaire. The questions and answer options are being pulled from a database using an API. Some of the options include images, with the image link stored in the database. I am trying to find a solution where text ...

Sending a concealed input according to the chosen option

I'm attempting to send some hidden values to a Servlet via a form, but my goal is to only pass them if the user chooses a specific option. <!-- FORM ABOVE --> <input type="hidden" name="foo" id="foo" value="foo"> <input type="hidden ...

AngularJS: Issue with scope not updating across several views

Having one controller and two views presents a challenge. ClustersController angular.module('app.controllers').controller('ClustersController', [ '$scope', 'ClustersService', function($scope, ClustersService) { ...

Is it possible to meta-refresh a page for redirection?

When creating a webpage, I included a META tag like this: <META http-equiv="refresh" content="5;URL=http://www.google.com"> The issue is that mobile browsers do not support this meta tag. It redirects properly on web browsers, but not on mobile dev ...

Does client-side JS/Angular have an HTTP Connection Timeout feature?

I'm currently using Angular's HttpClient to send HTTP requests and I want to set a specific timeout for them. Although I am aware that I can utilize HTTPInterceptors and include a timeout in RxJS operators, these settings apply to the entire req ...

Unable to render Material Icons on Vue/Quasar web app hosted on Azure

I am facing an issue with my webapp built using Vue and Quasar. I added the necessary icon imports to my quasar-user-options.js file. import '@quasar/extras/material-icons/material-icons.css' import "@quasar/extras/material-icons-outlined/ma ...

Steps for implementing a conditional statement to handle an empty string in HTML

I need to figure out how to display a different message if my string is empty. Can anyone help me with this? <div class="padding" id="dealBorder"> <pre id="informationDealText"><pan class="inner-pre" style="font-size: 24px; color: whi ...

What is the best way to connect with the <progress> element?

Vuex.Store({ state: { percentage: 0, }, ... I'm attempting to use the code <progress max="100" v-model="percentage"></progress>, but I keep encountering the error message 'v-model' directives are not supported on <pro ...

Using d3 to showcase pictures sourced from a csv file

Having recently embarked on a journey to learn javascript, d3, and the polymer project, I am facing a challenge that I hope to get some guidance on. After successfully parsing a csv file containing image information and creating an array specifically for ...

Is there a way to cancel hiding on a q-dialog?

I'm currently working on integrating a confirmation modal within a dialog box that includes form input fields. The purpose is to alert the user when they try to exit without saving their changes. The modal should appear every time the user modifies th ...

What are the steps to showcase a multiplication chart based on user-inputted rows and columns using jQuery?

I'm currently facing some challenges with coding a multiplication table using jQuery. I already have the code to display the multiplication table based on inputted rows, but I need help in modifying it to allow for inputting both rows and columns. An ...