我正在使用Nuxt.js构建一个静态网站。
如何在组件的script
代码中访问当前显示的路由名称(我想避免直接从浏览器位置读取URL)?
我能否以某种方式访问$route.name
?
我正在使用Nuxt.js构建一个静态网站。
如何在组件的script
代码中访问当前显示的路由名称(我想避免直接从浏览器位置读取URL)?
我能否以某种方式访问$route.name
?
是的,您可以使用Vue.js路由对象,例如$route.name
或$route.path
$nuxt.$route.path
返回当前路径
$nuxt.$route.name
当前路由的名称,如果有的话。
路由对象表示当前活动路由的状态。它包含当前URL的解析信息和与URL匹配的路由记录。
$route.path
类型:字符串
一个字符串,等于当前路由的路径,始终解析为绝对路径。例如 "/foo/bar"。
$route.fullPath
类型:字符串
包括查询和哈希的完整解析URL。
**
如果你想获取URL参数,就像这样: data() {
return {
zone: this.$nuxt.$route.query.zone,
jour: this.$nuxt.$route.query.jour
} },
**
在Vue2中
另一种方法是使用以下任意一种:
this.$route.path
→ 例如在 http://localhost:3000
上,{{this.$route.path}}
将打印出 /
this.$route.name
→ 例如在 http://localhost:3000
上,{{this.$route.name}}
将打印出 index
使用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>
如我之前在这里回答的一样:https://dev59.com/-FYN5IYBdhLWcg3wCEPa#72212136
export default ({
setup () {
const route = useRoute()
return {
route
}
}
})
在模板中的后面
{{ route.name }}
对于 Nuxt 3,您可以使用来自路由器的 currentRoute。
const { currentRoute } = useRouter();
const routeName = currentRoute.value.name;
对于 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 }
},
})
<script setup>
const route = useRoute(); // built-in composable
// route.name
useHead( function() {
return {
htmlAttrs: {
"data-route": route.name,
},
};
});
</script>
this.$route.name
。 - Belmin Bedak