DEV Community

loading...

Refactoring Vue Templates in Nuxt

cwraytech profile image Christopher Wray Updated on ・2 min read

Well, as soon as we start updating HTML in multiple places, it is time to start refactoring.

In order to make your HTML as reusable as possible, you should build components for all the parts of the HTML that you are using in multiple places.

With Nuxt, it is easy to do.

To reuse HTML, you can build Vue components in the components directory, and your components will automatically be registered whenever you use them in a page or another component.

Here is one of my components for a page header:

<template>
  <section>
      <div
        class="py-10 mx-auto max-w-screen-xl px-4 sm:py-12 sm:px-6 md:py-16 lg:py-20 xl:py-28"
      >
        <div class="text-center">
          <h1
            class="text-4xl tracking-tight leading-10 font-extrabold text-gray-900 sm:text-5xl sm:leading-none md:text-6xl"
          >
            {{ title }}
          </h1>
          <p
            class="mt-3 max-w-md mx-auto text-base text-gray-500 sm:text-lg md:mt-5 md:text-xl md:max-w-3xl"
          >
            {{ subtitle }}
          </p>
        </div>
      </div>
    </section>
</template>

<script>
export default {
  props: ['title', 'subtitle']
}
</script>
Enter fullscreen mode Exit fullscreen mode

And here is that component being used within a page template:

<template>
  <div>
    <!-- This is the Component above -->
    <PageHeader :title='projectPage.title' :subtitle='projectPage.subtitle' />
    <!-- This is another Component I built -->
    <ProjectList :projects='projects' />
  </div>
</template>
Enter fullscreen mode Exit fullscreen mode

As you may notice, I am using vue props for the content so that I can use the same header on multiple pages, but only change the content. This will make maintenance and updates so much faster because I will only have to update the HTML in one place.

Now, you can see the live site at chriswray.dev. Would love to know what you think!

Discussion (0)

pic
Editor guide