[英]Nuxt.js: How to use the same page with different URLs and switch the components to be displayed according to the URL
我想在Nuxt.js中实现以下内容:
1.使用相同的页面使用不同的URL。
具体来说,我想将/pages/users/_userId.vue
与/users/{userId}
, /users/{userId}/follow
和/users/{userId}/follower
。
我检查了一下,发现了以下问题。
-https://github.com/nuxt/nuxt.js/issues/2693
但这与我想要实现的目标有些不同。
我想将pass参数用作查询参数。
2.通过路径参数识别要显示的组件
在这里查看代码会更快。
・ / pages / users / _userId.vue`
<template>
<div class="user">
<div class="user__contents">
<div class="user__contents__main">
<UserInfo/>
<PostSection/> -> use if URL /users /{userId}
<FollowSection/> -> use if URL /users/{userId}/follow
<FollowerSection/> -> use if URL /users/{userId}/follower
</div>
</div>
</div>
</template>
<script>
import UserInfo from '~/components/organisms/users/UserInfo'
import PostsSection from '~/components/organisms/users/PostsSection'
import FollowSection from '~/components/organisms/users/FollowSection'
import FollowerSection from '~/components/organisms/users/FollowerSection'
...
我应该怎么做才能实现这些目标?
由于显示的组件取决于当前路由,因此可以使用路由器。 即使用nuxtjs嵌套路由功能。 (nuxtjs文档中的动态嵌套路由示例)
pages/
--| users/
-----| _id/
--------| follow.vue // contains FollowSection
--------| follower.vue // contains FollowerSection
--------| index.vue // contains UserProfile
-----| _id.vue
// users/_id.vue
<template>
<div class="user">
<div class="user__contents">
<div class="user__contents__main">
<UserInfo>
<NuxtChild
:user="user"
@custom-event="customEventHandler"
/>
</div>
</div>
</div>
<template>
您可以像下面这样将组件重用为嵌套页面:
// pages/users/_id/follower.vue
<script>
// don't create a template for the section
import FollowSection from '~/components/organisms/users/FollowSection'
export FollowSection
</script>
请注意,您不需要在_id.vue
导入子组件,因为nuxt会配置vue-router来这样做。 另外,您可以像传递常规组件一样传递道具并将事件发送给他们。
您可以通过设置项目目录结构来创建单个页面,而不是一页。 它将更易于处理和修改
pages/
--| users/
-----| _id/
--------| follow.vue
--------| follower.vue
-----| _id.vue
您所有的路径都有一个公共前缀users/
。 因此,您可以使用pages/users/_.vue
组件来匹配以users/
开头的,与其他任何组件都不匹配的路径。
在此组件中,您可以检查$nuxt.$route.params.pathMatch
以确定要显示的子组件。 在users/
之后,它将包含路径的一部分:
<template>
<div class="user">
<div class="user__contents">
<div class="user__contents__main">
<UserInfo />
<PostSection v-if="/^\d+$/.test(path)" />
<FollowSection v-else-if="/^\d+\/follow$/.test(path)" />
<FollowerSection v-else-if="/^\d+\/follower$/.test(path)" />
</div>
</div>
</div>
</template>
<script>
export default {
computed: {
path() {
return this.$nuxt.$route.params.pathMatch;
},
},
...
};
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.