Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Navigation: NuxtLink and navigateTo

Moving between pages in Nuxt does not reload the site: only the content of <NuxtPage /> changes, and the JavaScript already loaded stays. Links use the <NuxtLink> component, and navigation from code uses the navigateTo function.

Add a menu to app/app.vue:

<!-- app/app.vue -->
<template>
  <div>
    <NuxtRouteAnnouncer />
    <header>
      <nav>
        <NuxtLink to="/">Home</NuxtLink>
        <NuxtLink to="/posts">Posts</NuxtLink>
        <NuxtLink to="/about">About</NuxtLink>
      </nav>
    </header>
    <main>
      <NuxtPage />
    </main>
  </div>
</template>

<NuxtLink> renders an ordinary <a> tag but intercepts the click and changes the page without a reload. Click through the menu: the browser address changes and the header does not flicker.

Nuxt adds the class router-link-active to a link to the current page, and router-link-exact-active when the address matches exactly. Use them to highlight the menu item:

<!-- app/app.vue -->
<style>
nav a.router-link-exact-active {
  font-weight: bold;
}
</style>

The menu item of the current page becomes bold.

<NuxtLink> also understands full addresses:

<NuxtLink to="https://nuxt.com">Nuxt website</NuxtLink>

For an external address Nuxt renders a regular link that reloads the page. The target="_blank" attribute opens it in a new tab.

Sometimes you need to navigate after an action, for example after a button click. That is what navigateTo is for:

<!-- app/pages/about.vue -->
<script setup lang="ts">
async function goToPosts() {
  await navigateTo('/posts')
}
</script>
 
<template>
  <section>
    <h2>About the blog</h2>
    <button @click="goToPosts">Read the posts</button>
  </section>
</template>

The button opens the /posts page. navigateTo is imported automatically, so you do not import it yourself.

CallWhat it does
navigateTo('/posts')Goes to an address
navigateTo({ path: '/posts', query: { page: 2 } })Goes to /posts?page=2
navigateTo('/login', { replace: true })Goes without a new history entry
navigateTo('https://nuxt.com', { external: true })Goes to another site

Prefetching

When a <NuxtLink> appears on screen, Nuxt loads the code of the page it points to in advance. That is why following a link usually feels instant.

Common mistake

A link like <a href="/posts"> also works, but the browser reloads the whole site: the JavaScript downloads again and the app state is reset. For addresses inside the site always use <NuxtLink to="...">, and keep <a> for files such as PDFs.

Thanks for reading!

Donate to the site — we work hard for you.