简体   繁体   English

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

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

I'm using Nuxt.js for building a static website.我正在使用 Nuxt.js 构建一个 static 网站。

How to access in component's script code currently displayed route name (I would like to avoid reading direct url from browser location)?如何在组件的script代码中访问当前显示的路由名称(我想避免从浏览器位置直接读取 url)?

Can I somehow access $route.name ?我能以某种方式访问$route.name吗?

yes you can use vuejs route objects like $route.name or $route.path是的,您可以使用 vuejs 路由对象,例如$route.name$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.它包含当前 URL 的解析信息和该 URL 匹配的路由记录。

  • $route.path $route.path

    • type: string类型:字符串

    • A string that equals the path of the current route, always resolved as an absolute path.等于当前路由路径的字符串,始终解析为绝对路径。 eg "/foo/bar".例如“/foo/bar”。

  • $route.fullPath $route.fullPath

    • type: string类型:字符串

    • The full resolved URL including query and hash.完整解析的 URL,包括查询和哈希。

** **

And if you want to get the url params.如果你想获取 url 参数。 Like this :像这样 : 在此处输入图像描述 You do this:你来做这件事:

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

    }   },

** **

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.pathhttp://localhost:3000上的示例, {{this.$route.path}}将打印/
  • this.$route.name → Example on http://localhost:3000 , {{this.$route.name}} will print index this.$route.namehttp://localhost:3000上的示例, {{this.$route.name}}将打印index

for Nuxt v2 useRouter composition API对于 Nuxt v2 useRouter组合 API

 import { computed, defineComponent, useRoute } from '@nuxtjs/composition-api' export default defineComponent({ setup() { const route = useRoute() const routeName = computed(() => route.value.name) return { routeName } }, })

With Nuxt3 and Composition API, you can achieve that with this使用 Nuxt3 和 Composition API,您可以通过以下方式实现

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

Or with Options API或使用选项 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如我之前的回答所示: https ://stackoverflow.com/a/72212136/8816585

for Nuxt 3对于 Nuxt 3

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

after in template在模板之后

{{ route.name }}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM