Guide to importing a class property from one file to another - Using Vue with Typescript

Here is the code from the src/middlewares/auth.ts file:

import { Vue } from 'vue-property-decorator'

export default class AuthGuard extends Vue {
  public guest(to: any, from: any, next: any): void {
    if (this.$store.state.authenticated) {
      next()
      console.log('authenticated')
    } else {
      next({
        path: '/dashboard'
      })
      console.log('not authenticated')
    }
  }
}

This is the same auth.ts file but in its JavaScript version:

export default {
  guest(to, from, next) {
    if (this.$store.state.authenticated) {
      next()
      console.log('authenticated')
    } else {
      next({
        path: '/dashboard'
      })
      console.log('not authenticated')
    }
  }
}

The functionality works correctly with JavaScript, but not when using TypeScript.

I am trying to import this class into AuthRoutes.ts:

import Guard from '@/middlewares/auth'

export default [
  {
    path: '/',
    name: 'login',
    component: () => import('@/views/Login.vue'),
    beforeEnter: Guard.guest
  }
]

However, I am encountering an error that says: "Property 'guest' does not exist on type 'typeof AuthGuard'." I am still struggling to understand these TypeScript types. What could I be missing here?

Answer №1

Avoid using the beforeEnter method if you require access to the component instance.

The property belongs to the component instance, not the class definition.

beforeEnter does not provide access to the instance.

Instead, place your logic in the created() or mounted() method of the component and precede it with this..

Utilize beforeRouteEnter and beforeRouteUpdate for accessing the component's this.

The beforeRouteEnter guard does NOT grant access to this, as the guard is executed before confirming navigation, meaning the new entering component has not yet been created.

You can still access the instance by providing a callback to next. The callback will be triggered upon confirmation of navigation, passing the component instance as an argument:

beforeRouteEnter (to, from, next) {
  next(vm => {
    // access the component instance through `vm`
  })
}

For example:

beforeRouteEnter (to, from, next) {
  next(vm => {
    vm.guest
  })
}

And for route modifications preserving the component:

beforeRouteUpdate (to, from, next) {
  this.guest
}

Refer to Official Documentation

beforeRouteEnter (to, from, next) {
    // called before confirming the route that renders this component.
    // Does NOT have access to the `this` instance of the component,
    // as it hasn't been created at this guard's execution.
  },
beforeRouteUpdate (to, from, next) {
    // invoked when the rendering route of this component changes,
    // preserving the existing component in the new route.
    // Provides access to the `this` component instance.
  },

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

Does moment/moment-timezone have a feature that allows for the conversion of a timezone name into a more easily comprehendible format?

Consider this example project where a timezone name needs to be converted to a more readable format. For instance: input: America/Los_Angeles output: America Los Angeles While "America/Los_Angeles" may seem human-readable, the requirement is to convert ...

Updating $data within a VueJS directiveIs there something else you

We have a component and a directive. The structure of our component data is as follows: { langs: [ { title: '', content: '' }, { title: '', content: ...

How do I test Pinia by calling one method that in turn calls another method, and checking how many times it has been called

As I embark on my journey with Vue 3 and Pinia, a particular question has been lingering in my mind without a concrete answer thus far. Let's delve into the crux of the matter... Here's an example of the store I am working with: import { ref, co ...

Whenever a file is chosen, I aim to generate the video HTML dynamically and display the video with play functionalities using Angular 2 and TypeScript

I am attempting to allow users to select a video file and display it so they can play it after choosing the file. Below is my HTML code: <br> <input type="file" (change)="fileChangeEvent($event)" placeholder="upload file..." class=" ...

Transferring dynamic slots through parent, child, and grandchild components

Is there a way to pass dynamic slots from parent components all the way down to grandchildren? I have experience with static named slots, but I'm unsure about how to deal with dynamic named slots. For instance, let's assume that the slot templa ...

Implementing conditional asynchronous function call with identical arguments in a Typescript React project

Is there a way in React to make multiple asynchronous calls with the same parameters based on different conditions? Here's an example of what I'm trying to do: const getNewContent = (payload: any) => { (currentOption === myMediaEnum.T ...

Display images in a list with a gradual fade effect as they load in Vue.js

In my Vue project, I am looking to display images one at a time with a fading effect. I have added a transition group with a fade in effect and a function that adds each image with a small delay. However, I am facing an issue where all the images show up ...

Troubleshooting Vue.js nested v-for with <tr> tag problem

Why does Vue complain about undefined properties when I try nesting a <tr> inside a <tr> with a v-for binding on each? <table> <thead></thead> <tbody> <tr v-for="item in items"> <td>{{ item.nam ...

Tips for correctly loading images and spritesheets using Phaser 3 and Webpack

I am currently working on a Vue app using Webpack and Phaser 3. My main goal is to properly load images and spritesheets in the main scene of the game. import Phaser from 'phaser' export class MainScene extends Phaser.Scene { constructor () { ...

A guide on transferring JSON data from a Django view to Vue.js instance methods

Looking for assistance with Vue.js - I'm new to it. How can JSON data be passed from a Django view to a Vue instance (method)? Views.py def articles(request): model = News.objects.all() # getting News objects list random_generator = rando ...

Developing a collection of reusable components in a Javascript bundle for enhanced efficiency

I currently have a backend rendered page (using Django) that I want to enhance by incorporating components from PrimeVue and a markdown editor wrapped as a Vue component. Previously, we utilized some simple animations with jQuery which we included directly ...

Tips for styling the Button component in the shadcn/ui library for maximum impact

I'm currently working on a project using the shadcn/ui library. How can I properly customize it to meet my specific needs? For example, let's say I require an extra large red rounded Button for a call-to-action button in my project. What would be ...

Creating powerful Vue event handlers with composable functions

I am currently working with Vue 2.0, ES6, and Webpack. In my project, I have a Parent component and several child components called text-input. Each text-input emits a change event that should modify a different property inside the Parent component. For i ...

Tips for transforming an Observable stream into an Observable Array

My goal is to fetch a list of dogs from a database and return it as an Observable<Dog[]>. However, whenever I attempt to convert the incoming stream to an array by using toArray() or any other method, no data is returned when calling the retrieveDo ...

What is the process for importing a component along with all its dependencies?

I have a script where I am attempting to import a component and utilize its dependencies in the template. Specifically, I am looking to locally register a component FooComponent and use SharedComponent within the template of BarComponent. In Angular 2, one ...

I am looking for information on how to properly handle HTTP errors in Axios when utilizing a blob responseType in VueJs

Using the blob responseType with Axios in my VueJS app allows me to download a document from the server. Everything works fine when the response code is 200, but problems arise when there's an HTTP error. I find it challenging to read the status code ...

What is the best way to display a child component for every object while considering specific conditions?

I find myself wanting to use both v-for and v-if together, even though I know it's not doable. In a nutshell, my goal is to display a child component for each item in a prop. However, I also need to extract specific data from these items in order to ...

Application fails to launch after disabling unsafe-eval in the restricted Content Security Policy settings

Description My application is facing issues due to having a restricted CSP policy that does not allow unsafe-eval for scripts. When I add a Content-Security-Policy header without unsafe-eval, my application fails to load. Minimal Reproduction The restric ...

What is the most efficient method for sending query parameters through a URL in Vue.js with Axios?

My goal is to use Axios upon page load to retrieve a JSON object from the base URL. When a button is clicked, I want to append query parameters to the URL and fetch a different JSON object. For example, if the base URL is 'test.com', clicking the ...

What classification should be given to children when they consist solely of React components?

I'm encountering an issue where I need to access children's props in react using typescript. Every time I attempt to do so, I am faced with the following error message: Property 'props' does not exist on type 'string | number | boo ...