In Nuxt 3, passing parameters to the server or API primarily involves two aspects: route parameters and query parameters.
1. Using Route Parameters
In Nuxt 3, you can pass parameters through dynamic routing. For example, suppose you have a user profile page; you can set up a dynamic route to receive a user ID. The route file can be named pages/users/[id].vue.
In this file, you can use the useRoute function to retrieve route parameters:
javascript<script setup> import { useRoute } from 'vue-router' const route = useRoute() const userId = route.params.id </script>
You can then use this userId to initiate an API request to fetch the user's details. For example:
javascriptimport { useFetch } from 'nuxt/app' const { data: userInfo } = useFetch(`/api/users/${userId}`)
2. Using Query Parameters
Query parameters are typically used for filtering or searching requests. For example, if you want to search for users by username, you can include a query string in the API request.
In Nuxt 3, you can use useRoute to retrieve query parameters:
javascript<script setup> import { useRoute } from 'vue-router' const route = useRoute() const searchQuery = route.query.search </script>
You can then use this query parameter to construct your API request:
javascriptimport { useFetch } from 'nuxt/app' const { data: searchResults } = useFetch(`/api/users?search=${searchQuery}`)
Example: User Search Page
Suppose we are developing a user search page in a Nuxt 3 application where users can input a search term to find specific users. Here is a simple example of this page:
Page Component:
vue<template> <div> <input v-model="searchTerm" @input="fetchSearchResults" placeholder="Search users..."> <ul> <li v-for="user in users" :key="user.id">{{ user.name }}</li> </ul> </div> </template> <script setup> import { ref } from 'vue' import { useFetch } from 'nuxt/app' const searchTerm = ref('') const { data: users } = useFetch('/api/users', { watch: [searchTerm], params: { search: searchTerm } }) const fetchSearchResults = () => { users.refresh() } </script>
In this example, whenever a user types in the search box, the fetchSearchResults function is triggered, and useFetch re-fetches the data with the new query parameters. This is a practical example demonstrating how to handle dynamic query parameters in Nuxt 3.