如何获取Vue中路线的当前名称?

Isa*_*edo 9 vue.js vue-router

我想获取vue-router当前路由的名称,我有一个带有导航到其他componentes的组件菜单,因此我想显示当前路由的名称。我有这个:

created(){
    this.currentRoute;
    //this.nombreRuta = this.$route.name;
},
computed:{
    currentRoute:{
        get(){
            this.nombreRuta = this.$route.name;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是路由名称的标签不会更改,标签仅显示第一个加载的路由的名称。谢谢

编辑:

在此处输入图片说明

显示我想要的图像

ssc*_*ep3 20

您使用computed不正确。您应该在函数中返回该属性。有关更多信息,请参阅文档

这是您的改编示例:

computed: {
    currentRouteName() {
        return this.$route.name;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后可以像这样使用它:

<div>{{ currentRouteName }}</div>
Run Code Online (Sandbox Code Playgroud)

您还可以直接在模板中使用它,而无需使用计算属性,如下所示:

<div>{{ $route.name }}</div>
Run Code Online (Sandbox Code Playgroud)

  • 确保在使用“this.$route.name”之前,您已在路由器中的每个路由上正确定义了“name” (3认同)
  • @ ali6p我认为,您的意思是`$ router.currentRoute`(在末尾有一个附加的`r`)。这个命令返回$ route对象。另请参见https://router.vuejs.org/api/#router-currentroute和https://router.vuejs.org/api/#the-route-object (2认同)

Kit*_*Kit 11

Vue 3 + Vue 路由器 4

2021 年 3 月 5 日更新

如果您使用的是Vue 3Vue Router 4,这里有两种最简单的方法来获取setup钩子中路由的当前名称:

解决方案1:使用useRoute

import { useRoute } from 'vue-router';
export default {
  setup () {
    const currentRoute = computed(() => {
      return useRoute().name
    })
    return { currentRoute }
  }
}
Run Code Online (Sandbox Code Playgroud)

解决方案2:使用useRouter

import { useRouter } from 'vue-router';
export default {
  setup () {
    const currentRoute = computed(() => {
      return useRouter().currentRoute.value.name;
    })
    return {currentRoute}
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 我没有使用“setup()”,而是在模板中使用“compulated: {route: () =&gt; useRoute() }”,然后使用“{{route.name }}” (2认同)

Ani*_*udh 10

在 Composition API 中,这有效

import { useRouter } from 'vue-router'

const router = useRouter()

let currentPathObject = router.currentRoute.value; 
 
console.log("Route Object", currentPathObject)

// Pick the values you need from the object
Run Code Online (Sandbox Code Playgroud)


小智 9

我用这个...

this.$router.history.current.path
Run Code Online (Sandbox Code Playgroud)

  • 感谢您的贡献。你能解释一下为什么它可以解决OP的问题吗?你为什么“用这个”?解释可以帮助未来的用户,增加长期价值,质量更高,并且更有可能被投票。考虑进行编辑以添加更多上下文。 (7认同)