Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Watch route changes in Vue.js with Typescript

Tags:

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?

like image 691
luthien Avatar asked Aug 17 '18 09:08

luthien


People also ask

How does Vue know route change?

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.

How do I see previous routes on Vue?

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.

Does TypeScript work with Vue?

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.


1 Answers

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     } 
like image 200
luthien Avatar answered Sep 19 '22 08:09

luthien