Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access routing parameters in Vue.js - Nuxt - TypeScript application?

I'm building a website that is based on Nuxt TypeScript Starter template. I've created a dynamically routed page _id.vue inside of my pages folder and I want to have access to that id property inside of my TS class. I can access it in my template by writing {{$route.params.id}} but when I try to reference $route inside of the class I get an error:

error TS2304: Cannot find name '$route'.

like image 1000
Andrew Bogdanov Avatar asked Jan 22 '18 16:01

Andrew Bogdanov


People also ask

Does Nuxt support Vue router?

Nuxt automatically generates the vue-router configuration for you, based on your provided Vue files inside the pages directory. That means you never have to write a router config again! Nuxt also gives you automatic code-splitting for all your routes.

How do I get the path in Nuxt?

To get the current route path in nuxt, we can use this. $route. path or $this. $nuxt.


1 Answers

As a simple solution, try importing route from vue-router, like this:

<script lang="ts">
import Component from "vue-class-component"
import { Route } from "vue-router"

@Component({})
export default class RoutingExample extends Vue {
    created() {
        console.log(this.$route) // this should not throw TS errors now
    }

}
</script>

Other solutions I think would require you to augment the Vue module, something similar to what you'd find here in the Vue docs.

More Vue + TypeScript examples can be found in this repo: https://github.com/jsonberry/vue-typescript-examples

like image 71
Jason Awbrey Avatar answered Sep 24 '22 23:09

Jason Awbrey