How to use In-Component route guards in your Vue App
If you don’t know what an in-component router guard is or why you need one, quickly head over to the Vue official documentation. For my use-case, I needed to run some checks at the route level before the component to be interacted with by the user was even determined hence, I opted for the beforeRouteEnter
hook
This article assumes readers set up their codebases using the vue-property-decorators
, a package that extends the original vue-class-component
package for Typescript support, and with some other nice decorators like @Prop, @Watch
etc. Be sure to check it out.
using the in-component guards
- head over to the file that houses your root Vue instance, usually this would be the
main.js
or themain.ts
file if you set up your project with Typescript.
- Open the file and add this snippet immediately after your Vue component import, it is very important that this code goes before the Vue instance because you want to ensure it is registered with your Vue instance:
import Component from vue-class-component
Component.registerHooks([
'beforeRouteEnter',
'beforeRouteUpdate',
'beforeRouteLeave'
])
Now, you can call any of the in-component route guards within any of your components.