66

I'm using Nuxt.js for building a static website.

How to access in component's script code currently displayed route name (I would like to avoid reading direct url from browser location)?

Can I somehow access $route.name ?

kissu
  • 40,416
  • 14
  • 65
  • 133
lukaszkups
  • 5,790
  • 9
  • 47
  • 85

6 Answers6

133

In Nuxt2

yes you can use vuejs route objects like $route.name or $route.path

$nuxt.$route.path

return current path

$nuxt.$route.name

The name of the current route, if it has one.

Route Object Properties

A route object represents the state of the current active route. It contains parsed information of the current URL and the route records matched by the URL.

  • $route.path

  • type: string

  • A string that equals the path of the current route, always resolved as an absolute path. e.g. "/foo/bar".

  • $route.fullPath

  • type: string

  • The full resolved URL including query and hash.

**

And if you want to get the url params. Like this : enter image description here You do this:

  data() {
    return {
       zone: this.$nuxt.$route.query.zone,
       jour: this.$nuxt.$route.query.jour
        
    }   },

**

Kalnode
  • 9,386
  • 3
  • 34
  • 62
Mohammad Fanni
  • 4,095
  • 3
  • 28
  • 52
  • My URL contains some characters after a hash sign. Not path nor name returns the value after # /my/url/#somemore only /my/url/ is returned – Arman Fatahi Aug 16 '18 at 11:22
24

In Vue2

An alternative way is to use either of the following:

  • this.$route.path → Example on http://localhost:3000 , {{this.$route.path}} will print /
  • this.$route.name → Example on http://localhost:3000, {{this.$route.name}} will print index
Kalnode
  • 9,386
  • 3
  • 34
  • 62
Billal Begueradj
  • 20,717
  • 43
  • 112
  • 130
17

With Nuxt3 and Composition API, you can achieve that with this

<script setup>
const route = useRoute()
console.log('current name', route.name)
</script>

Or with Options API

<script>
export default {
  mounted () {
    console.log('current name', this.$route.name)
  },
}
</script>

As shown in my previous answer here: https://stackoverflow.com/a/72212136/8816585

kissu
  • 40,416
  • 14
  • 65
  • 133
5

for Nuxt 3

export default ({
   setup () {
    const route = useRoute()
    return {
      route
    }
  }
})

after in template

{{ route.name }}
2

for Nuxt v2 useRouter composition API

import { computed, defineComponent, useRoute } from '@nuxtjs/composition-api'

export default defineComponent({
   setup() {
       const route = useRoute()
       const routeName = computed(() => route.value.name)
       return { routeName }
   },
})
1

For Nuxt 3 you can use currentRoute from router.

const { currentRoute } = useRouter();
const routeName = currentRoute.value.name;