[Vuejs]-How do I properly type navigation guards in Nuxt class components?

0๐Ÿ‘

  1. You should register the registerHooks lifeCycle in your custom plugin and register it in nuxt.config.ts.
// plugin/main.ts
import 'vue-class-component/hooks' // auto registerHooks

// nuxt.config.ts
import type { NuxtConfig } from '@nuxt/types';
const config: NuxtConfig = {
     plugins: [ { src: '~/plugins/main.ts' } ]
     // ignore other...
};
export default config;
  1. According to doc the beforeRouteLeave have two or three parameter not four so just fix the code and it will work fine.
// MyComponent.vue
import { Component, Vue } from "nuxt-property-decorator"
import { NavigationGuardNext, Route } from 'vue-router';

@Component
export default class MyComponent extends Vue {  
  beforeRouteLeave(to: Route, from: Route, next: NavigationGuardNext) {
    // will call the foo() function
    this.foo()
    next()
  }

  foo () { console.log("navigation guard triggered") }
}
  1. If your VSCode still showing missing the type, you can create the shims-vue.d.ts to help Typescript understand the type. Here is doc.

Leave a comment