In this tutorial, we will delve into the use of named routes in Nuxt.js. Named routes are a way to uniquely identify routes in your application, which makes it easier to navigate within your app.
By the end of this tutorial, you will be able to:
Prerequisites:
Nuxt.js automatically generates the vue-router configuration by parsing your Vue files inside the pages
directory. To create a named route, you simply have to create a .vue
file in the pages
directory.
For example, if you create a file named about.vue
in the pages
directory, Nuxt.js will automatically create a route named 'about' that maps to this file.
To navigate to a named route, you can use the <nuxt-link>
component's to
prop or the router.push()
method.
Example 1: Creating a Named Route
about.vue
in the pages
directory:<template>
<div>
<h1>About</h1>
<p>This is the about page</p>
</div>
</template>
This will automatically create a route named 'about' that maps to this file.
Example 2: Navigating to a Named Route
<nuxt-link>
component to navigate to the 'about' page:<nuxt-link to="/about">About</nuxt-link>
router.push()
method:this.$router.push({ name: 'about' });
In this tutorial, we learned about named routes in Nuxt.js, how to create them, and how to navigate to them using either the <nuxt-link>
component or the router.push()
method. As next steps, you might want to explore more about dynamic routes in Nuxt.js.
Solution:
// pages/contact.vue
<template>
<div>
<h1>Contact</h1>
<p>This is the contact page</p>
</div>
</template>
// pages/about.vue
<template>
<div>
<h1>About</h1>
<p>This is the about page</p>
<nuxt-link to="/contact">Contact</nuxt-link>
</div>
</template>
Solution:
// pages/about.vue
<template>
<div>
<h1>About</h1>
<p>This is the about page</p>
<button @click="goToContact">Go to Contact</button>
</div>
</template>
<script>
export default {
methods: {
goToContact() {
this.$router.push({ name: 'contact' });
},
},
};
</script>
Keep practicing and exploring more complex routing scenarios. Happy coding!