我想获取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)
Kit*_*Kit 11
Vue 3 + Vue 路由器 4
2021 年 3 月 5 日更新
如果您使用的是Vue 3和Vue 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)
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)