Nuxt 3 Tutorial Series: Part 2 - Routing Basics and Components

In Part 1 of our tutorial series, we introduced Nuxt.js and discussed its key features. Now, in Part 2, we'll delve into routing basics and components in Nuxt.js, two fundamental concepts for building web applications. Let's get started!

Routing Basics in Nuxt.js

Routing in Nuxt.js is handled seamlessly thanks to its integration with Vue Router. Nuxt.js automatically generates routes based on the file structure of your project, making it intuitive to create and manage routes.

Creating Pages

In Nuxt.js, each .vue file in the pages directory corresponds to a route in your application. For example, a pages/about.vue file will create a route for the /about URL.

<!-- pages/about.vue -->

<template>
  <div>
    <h1>About Us</h1>
    <p>Welcome to our website!</p>
  </div>
</template>

 

Navigation

You can navigate between pages using <nuxt-link> components, which are similar to Vue Router's <router-link> components.

<template>
  <div>
    <h1>Home</h1>
    <nuxt-link to="/about">About</nuxt-link>
  </div>
</template>

Components in Nuxt.js

Components are reusable UI elements in Vue.js applications, and Nuxt.js makes it easy to create and use components within your project.

Creating Components

To create a component in Nuxt.js, you can simply define a .vue file in the components directory.

<!-- components/Header.vue -->

<template>
  <header>
    <h1>{{ title }}</h1>
  </header>
</template>

<script>
export default {
  data() {
    return {
      title: 'My Awesome Website'
    };
  }
};
</script>

Using Components

Once created, you can use components in your pages by importing them and including them in your template.

<!-- pages/index.vue -->

<template>
  <div>
    <Header />
    <p>Welcome to my website!</p>
  </div>
</template>

<script>
import Header from '~/components/Header.vue';

export default {
  components: {
    Header
  }
};
</script>

Conclusion

In this part of the tutorial series, we explored the basics of routing and components in Nuxt.js. Routing is handled effortlessly, allowing you to focus on building out your application's pages. Components provide a way to create reusable UI elements, enhancing code organization and maintainability.

In Part 3, we'll dive deeper into layouts and views in Nuxt.js, exploring how they help maintain a consistent structure across your application. Stay tuned!

If you have any questions or need further clarification, feel free to ask. Happy coding!

Press ESC to close