Nuxt.js: How to use the same page with different URLs and switch the components to be displayed according to the URL Nuxt.js: How to use the same page with different URLs and switch the components to be displayed according to the URL vue.js vue.js

Nuxt.js: How to use the same page with different URLs and switch the components to be displayed according to the URL


As the displayed components depends on the current route, you can use the router.Namely using the nuxtjs nested routes feature. (example of dynamic nested routes in nuxtjs docs)

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>

You can reuse the components as nested pages like that:

// pages/users/_id/follower.vue<script> // don't create a template for the sectionimport FollowSection from '~/components/organisms/users/FollowSection'export default FollowSection</script>

Note that you don't need to import the child components in _id.vue because nuxt configure vue-router to do so. Also that you can pass props and send events to them like normal components.


All your paths have a common prefix users/. So you can use the pages/users/_.vue component to match any path starting with the users/ that was not matched to any other component.

In this component you can examine $nuxt.$route.params.pathMatch to decide, which subcomponent to show. It will contain part of path after 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>


Instead of one page , you can create individual page by setting your project directory structrue like this . It will more easy to handle and modify

pages/--| users/-----| _id/--------| follow.vue--------| follower.vue-----| _id.vue