簡體   English   中英

Nuxt.js:如何在具有不同URL的同一頁面上使用以及如何根據URL切換要顯示的組件

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM