如何在Nuxt.js中获取当前路由名称?

luk*_*ups 16 vue.js vue-router vue-component vuejs2 nuxt.js

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

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

我可以以某种方式访问$route.name

Moh*_*d b 35

是的,你可以使用像$route.name或的vuejs路由对象$route.path

$nuxt.$route.path
Run Code Online (Sandbox Code Playgroud)

返回当前路径

$nuxt.$route.name
Run Code Online (Sandbox Code Playgroud)

当前路由的名称(如果有).

路由对象属性

路由对象表示当前活动路由的状态.它包含当前URL的解析信息以及URL匹配的路由记录.

  • $ route.path

    • type:string

    • 一个等于当前路径路径的字符串,始终解析为绝对路径.例如"/ foo/bar".

  • $ route.fullPath

    • type:string

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


kis*_*ssu 19

借助 Nuxt3 和 Composition API,您可以通过以下方式实现这一目标

<script setup>
const route = useRoute()
console.log('current name', route.name)
</script>
Run Code Online (Sandbox Code Playgroud)

或者使用选项 API

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

如我之前的回答所示:https ://stackoverflow.com/a/72212136/8816585


Bil*_*adj 18

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

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


Ale*_*lov 6

适用于 Nuxt 3

export default ({
   setup () {
    const route = useRoute()
    return {
      route
    }
  }
})
Run Code Online (Sandbox Code Playgroud)

在模板之后

{{ route.name }}
Run Code Online (Sandbox Code Playgroud)


Pav*_*sky 5

对于 Nuxt 3,您可以使用路由器中的 currentRoute。

const { currentRoute } = useRouter();
const routeName = currentRoute.value.name;
Run Code Online (Sandbox Code Playgroud)