如何在 Nuxt 2 和 3 中获取当前路由名称?

How to get current route name in Nuxt 2 and 3?

我正在使用 Nuxt.js 构建静态网站。

如何在组件的 script 代码中访问当前显示的路由名称(我想避免从浏览器位置直接读取 url)?

我能以某种方式访问​​ $route.name 吗?

是的,您可以使用 vuejs 路由对象,例如 $route.name$route.path

$nuxt.$route.path

return当前路径

$nuxt.$route.name

当前路由的名称,如果有的话。

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

    • 类型:字符串

    • 等于当前路由路径的字符串,始终解析为绝对路径。例如“/foo/bar”.

  • $route.fullPath

    • 类型:字符串

    • 完整解析 URL 包括查询和哈希。

**

And if you want to get the url params. Like this : You do this:

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

    }   },

**

另一种方法是使用以下任一方法:

  • this.$route.pathhttp://localhost:3000 上的示例,{{this.$route.path}} 将打印 /
  • this.$route.namehttp://localhost:3000{{this.$route.name}} 上的示例将打印 index

对于 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 }
   },
})

使用 Nuxt3 和 Composition API,你可以用这个

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

或使用选项 API

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

如我之前的回答所示: