Nuxt - Reuse Page Components in 2 simple steps

Most of the time in a CRUD app, the Create page and Edit page are entirely the same. How do you reuse the same page component then if you are using Nuxt?

Assuming you already have a "/create" page and wanted to reuse that page's component in "/edit/:name" route, here are 2 more steps you need to do:

  1. 1 - Edit nuxt.config.js and add new route.
  2. 2 - Handle the new route in the reused page component

For the sake of brevity of this page, I made a codesandbox project. Check it out here.

First, I created a create.vue page component which will then be reused by the "/edit/:name" route.

Next, for context of the following explanation, check out nuxt.config.js on codesandbox.

So what does the extendRoutes at line 50 there do?

extendRoutes will receive 2 arguments: all the route entries and a function for resolving a component. Since we created a "create.vue" page component, Nuxt will automatically register a route entry for that component which would look like:

{
  path: "/create",
  name: "create"
  component: <the create.vue component>
}

Now, all I have to do is find that "create" route, register the "/edit/:name" route, and use the component from "create" route.

extendRoutes(routes, resolve) {
  const createPage = routes.find(route => {
    return route.name === "create";
  });

  routes.push({
    path: "/edit/:name",
    name: "edit",
    component: createPage.component
  });
}

Lastly, how can we tell from the "create.vue" if we're creating or editing?

We just check the $route from the component and check the route name or path. And since we have access to the global $route object, we can also access the route params which is in this example, is the name and we'll be using it to populate our name input otherwise if it's not there, it's just empty.

<script>
export default {
  data() {
    return {
      name: this.$route.params.name
    };
  },

  computed: {
    pageTitle() {
      return this.$route.name === "create" ? "Create User" : "Edit User";
    }
  }
};
</script>

On a regular project though, it's usually an ID that you use when editing and then you'd fetch the data of the given ID from the server.

You can also do that with Nuxt using the asyncData() option. Just check if you're entering an "/edit/:name" route, get the id, fetch, and return it.

If you think that this strategy might cause confusion, my alternative suggestion would be to create another directory for reusable page components and add both the routes in nuxt.config.js and name the component UserFormPage.