In Nuxt.js, the nuxt-link component is the preferred method for internal routing within Vue applications. It leverages the functionality of
Basic Syntax of nuxt-link:
html<nuxt-link to="/about">About Us</nuxt-link>
Here, the to attribute specifies the route path of the link target. It works similarly to the href attribute in a standard tag but is better suited for Vue's reactive routing system.
Dynamic Routing:
If you need to create dynamic routes, you can use it as follows:
html<nuxt-link :to="`/user/${userId}`">User Information</nuxt-link>
Complete Example:
Assume we are building a blog platform where we need to navigate from the blog list to the blog detail page:
html<template> <div> <h1>Blog List</h1> <ul> <li v-for="post in posts" :key="post.id"> <nuxt-link :to="`/posts/${post.id}`">{{ post.title }}</nuxt-link> </li> </ul> </div> </template> <script> export default { data() { return { posts: [ { id: 1, title: "Fundamentals of Nuxt.js" }, { id: 2, title: "How to Use Vue" }, { id: 3, title: "Importance of Frontend Routing" } ] }; } } </script>
In this example, each nuxt-link uses :to to dynamically bind to the specific route of each article. This ensures that clicking any link navigates users to the corresponding article detail page.
Summary:
- Compared to using standard tags, using nuxt-link optimizes for Nuxt's server-side rendering and route lazy loading.
- Use the to attribute instead of href to specify the link destination.
- You can use JavaScript expressions to dynamically generate route paths.
By using the above methods, you can effectively implement internal navigation in your Nuxt.js application while maintaining performance and user experience.