Location>code7788 >text

Flexible Routing with navigateTo

Popularity:514 ℃/2024-08-13 10:01:54

title: Flexible Routing with navigateTo
date: 2024/8/13
updated: 2024/8/13
author: cmdragon

excerpt:
Abstract: This article introduces the navigateTo function in detail, including basic usage, use in routing middleware, navigation to external URLs and new tabs to open the link method, as well as parameter details and precautions, demonstrating the flexibility and power of the function in the programmatic navigation.

categories:

  • front-end development

tags:

  • Nuxtjs
  • routing (in computer networks)
  • navigator
  • program
  • Web
  • middleware
  • URL

image
image

scanningtwo-dimensional barcodeFollow or microsoft search:Programming Intelligence Front-End to Full-Stack Communication and Growth

utilizationnavigateTo Detailed Guide to Functions

navigateTo is a very powerful navigation helper that allows developers to programmatically navigate users, supporting both server-side and client-side environments.

What is it?navigateTo

navigateTo Allows us the flexibility to redirect to different routes in our own code. It can receive the destination path as a string or a route object and supports a variety of options to customize the navigation behavior.

basic usage

Using thenavigateTo Very simple. Here are some examples of common usage:

Navigating to simple paths


<script setup lang="ts">

  // Navigate to '/search'
  await navigateTo('/search')
</script>

Navigating to Route Objects

You can also pass route objects as parameters:


<script setup lang="ts">

  // Navigate using the route object
  await navigateTo({path: '/search'})
</script>

Routing objects with query parameters

If you need to add query parameters, you can do so:


<script setup lang="ts">

  // Navigate to the path with the query parameters
  await navigateTo({
    path: '/search', // navigate to the path with the query parameter await
    query: {
      page: 1, sort: 'asc', query: {
      sort: 'asc'
    }
  })
</script>

Use in routing middleware

navigateTo It can also be used in routing middleware to implement redirection:

// middleware/
export default defineNuxtRouteMiddleware((to, from) => {
    if ( !== '/search') {
        // Permanent redirect to '/search'
        return navigateTo('/search', {redirectCode: 301})
    }
})

Navigating to external URLs

By default, thenavigateTo Disallows navigation to external URLs; if desired, you can set theexternal parameters aretrue


<script setup lang="ts">

  // Navigate to externalURL
  await navigateTo('', {external: true})
</script>

Open link in new tab

If you want to open the link in a new tab, you can use theopen Options:


<script setup lang="ts">

  // Open link in new tab
  await navigateTo('', {
    open: {
      target: '_blank',
      windowFeatures: {
        width: 500,
        height: 500
      }
    }
  })
</script>

Parameter details

  • to:
    • typology: RouteLocationRaw | undefined | null
    • default value: '/'
    • account for: This is the destination route, either a string or a route object. When its value isundefined maybenull Default navigation to the root route when'/'

Optional parameters (options)

  • replace:

    • typology: boolean
    • default value: false
    • account for: If set totrue, then it will replace the current route with the new one instead of pushing it into the history.
  • redirectCode:

    • typology: number
    • default value: 302
    • account for: The status code to use when redirecting on the server side. It is possible to use the301 Indicates a permanent redirect.
  • external:

    • typology: boolean
    • default value: false
    • account for: If set totrueThe default is to disallow external links.
  • open:

    • typology: OpenOptions
    • account for: For use on the client side via the() method navigates to the URL. the server side ignores this option.

    Properties of OpenOptions.

    • target:

      • typology: string
      • default value: '_blank'
      • account for: Defines the name of the context in which the resource is loaded.
    • windowFeatures:

      • typology: OpenWindowFeatures
      • account for: This set of properties controls some of the characteristics of the new window, such as size and position.

      Properties of OpenWindowFeatures.

      • popup: boolean
      • width / innerWidth: number
      • height / innerHeight: number
      • left / screenX: number
      • top / screenY: number
      • noopener: boolean
      • noreferrer: boolean

Example: Use all options

Below is a complex example showing how to navigate using all the options:


<script setup lang="ts">

  // Examples of complex navigation
  await navigateTo('', {
    external: true,
    open: {
      target: '_blank',
      windowFeatures: {
        width: 800,
        height: 600,
        popup: true
      }
    }
  })
</script>

caveat

  • In the case of a call tonavigateTo Be sure to use theawait maybereturn handles its result because it returns a Promise.
  • When using the middleware, please pay attention to the selection of the redirection code and choose the appropriate status code according to the update status of the message.

summarize

navigateTo is a very powerful tool for navigating in a flexible and efficient way. Whether it's a simple routing jump or a complex external URL
Open up.navigateTo All can be easily realized

For the rest of the article, please click to jump to the personal blog page or scan the code to follow or WeChat search:Programming Intelligence Front-End to Full-Stack Communication and Growth, read the full article:Flexible Routing with navigateTo | cmdragon's Blog

Past articles are archived:

  • Page-level hybrid rendering with Nuxt 3's defineRouteRules | cmdragon's Blog
  • Getting to grips with Nuxt 3's page metadata: custom configurations with definePageMeta | cmdragon's Blog
  • Creating Route Middleware with defineNuxtRouteMiddleware | cmdragon's Blog
  • Defining Vue Components with defineNuxtComponent` | cmdragon's Blog
  • Detailed Guide to Creating Error Objects with createError | cmdragon's Blog
  • Clear Nuxt state cache: clearNuxtState | cmdragon's Blog
  • Clear Nuxt Data Cache: clearNuxtData | cmdragon's Blog
  • Clearing processed errors with clearError | cmdragon's Blog
  • Dynamically Adding Middleware with addRouteMiddleware | cmdragon's Blog
  • Blocking Navigation with abortNavigation | cmdragon's Blog
  • HTTP request using $fetch | cmdragon's Blog
  • Managing Responsive State with useState | cmdragon's Blog
  • Optimize your website for SEO with useServerSeoMeta | cmdragon's Blog
  • SEO Configuration with useSeoMeta | cmdragon's Blog
  • Must Read: Runtime Configuration Made Easy with useRuntimeConfig | cmdragon's Blog
  • Route Management: The useRouter Method and Routing Middleware Applications | cmdragon's Blog
  • UseRoute Function Details and Examples | cmdragon's Blog
  • Accessing a request URL using the useRequestURL combinatorial function | cmdragon's Blog
  • Configuring and Using Environment Variables | cmdragon's Blog