In Vue 3, you can pass parameters through the URL using query parameters (?key=value) instead of defining them as route parameters. This approach makes it easy to pass optional values without modifying the route structure.
1. Navigate with Query Parameters
Instead of using a dynamic route like /product/:id, you can pass query parameters while navigating:
<!-- Using a <router-link> -->
<router-link :to="{ path: '/product', query: { id: 123, name: 'Bag' } }">
Go to Product
</router-link>
2. Access Query Parameters in a Vue Component
Inside a Vue component, you can retrieve query parameters using useRoute():
<script setup>
import { useRoute } from 'vue-router';
const route = useRoute();
const productId = route.query.id; // "123"
const productName = route.query.name; // "Bag"
</script>
3. Programmatic Navigation with Query Params
You can also navigate with query parameters programmatically:
import { useRouter } from 'vue-router';
const router = useRouter();
router.push({ path: '/product', query: { id: 456, name: 'Backpack' } });
Benefits of Using Query Parameters:
- Optional: Unlike route params, query params don’t need to be predefined.
- Multiple Parameters: Easily pass multiple optional parameters.
- Easy Bookmarking: Query parameters persist in the URL, allowing for easy sharing or bookmarking.