<template>
<div>
<!-- 使用 query 传递参数(URL 的查询字符串) -->
<!-- to="/path?参数名=值" -->
<!-- <router-link to="/path?参数名=值"> -->
<!-- 接收传递的值 $route.query.参数名 -->
<router-link :to="{ name: 'UserProfile', query: { userId: 123 }}">
Go to User Profile with Query
</router-link>
<router-link :to="{ name: 'UserProfile', path: '/user/456' }">
Go to User Profile Directly with Path</router-link>
<!-- 接收传递的值 $route.params.参数名 -->
</div>
</template>
query
参数会直接附加在 URL 后面,作为查询字符串。- 直接在
:to
的path
属性中指定参数是最直接的方式,但这要求你提前知道完整的路径。
在 UserProfile
组件中,你可以通过 $route.query
来访问这些参数:
<script setup>
import { useRoute } from 'vue-router';
const route = useRoute();
// 存储 userId
const storedUserId = route.query.userId;
</script>