vue3 中的传参方式和vue2中一样,都可以用query和params传参。
不过注意的是,vue2 中是有this的,但是vue3是在setup中进行的,且要引入 useRoute 和useRouter。
传递的参数会显示在path上,页面刷新时数据不丢失。如下
http://localhost:3000/details?id=1
<script setup>
import {useRouter} from "vue-router"
const $router = useRouter()
let query = () => {
$router.push({
name: "Details",
query: {id: 1},
});
}
</script>
<script setup>
import {useRoute} from "vue-router";
const query = useRoute().query;
console.log(query)
</script>
传递的参数会显示到path中,页面刷新时数据不会丢失。如下
http://localhost:3000/details/1
//路由配置
{
path: '/details/:id',
component: () => import('@/views/details'),
}
<script setup>
import {useRouter} from "vue-router"
const $router = useRouter()
let params = () => {
$router.push(`/details/${id}`);
}
</script>
<script setup>
import {useRoute} from "vue-router";
const params = useRoute().params;
console.log(params)
</script>
传递的参数不会显示在path上,页面刷新时数据会丢失
//路由配置
{
path: '/details',
component: () => import('@/views/details'),
}
<script setup>
import {useRouter} from "vue-router"
const $router = useRouter()
let params = () => {
$router.push({
path: "/details",
params: {id: 1},
});
}
</script>
<script setup>
import {useRoute} from "vue-router";
const params = useRoute().params;
console.log(params)
</script>
参考文章 父子组件传参