I'd like to detect changes in my URL in a Vue.js application using TypeScript. In JavaScript this can be done as follows:
watch: { '$route': { handler: 'onUrlChange', immediate: true, deep: true } }, onUrlChange(newUrl){ // Some action }
How could I do the same in TypeScript?
To listen for route change events with Vue. js and Vue Router, we can watch the $route object in our component. to watch the $route in our component. We set deep to true to watch for all changes in the $route object's contents.
To get previous page URL with Vue Router, we can get it from the from parameter of the beforeRouterEnter hook. to add the beforeRouteEnter hook into our component and get the previous page URL from the from parameter.
Now that Vue. js officially supports TypeScript, it's possible to create TypeScript projects from scratch using Vue CLI. However, you still need some third-party packages with custom decorators and features to create a true, complete TypeScript application.
I found the solution here: https://github.com/kaorun343/vue-property-decorator
It can be done like this:
@Watch('$route', { immediate: true, deep: true }) onUrlChange(newVal: any) { // Some action }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With