栽Vue3中傳遞路由參數(shù)的三種方式
更新時間:2024年07月31日 09:39:57 作者:ksuper&
vue 路由傳參的使用場景一般都是應用在父路由跳轉到子路由時,攜帶參數(shù)跳轉,傳參方式可劃分為 params 傳參和 query 傳參,本文將給大家介紹如何通過不同方式在 Vue 3 中傳遞路由參數(shù),需要的朋友可以參考下
如何通過不同方式在 Vue 3 中傳遞路由參數(shù),并在組件中使用 defineProps 或其他組合式 API 獲取這些參數(shù)?
1. 通過 path 參數(shù)傳遞
最常見的方式,通過在路由路徑中定義動態(tài)參數(shù),并在路由配置中設置 props: true,將參數(shù)作為 props 傳遞給組件。
路由配置
{
path: '/:projectId(\\d+)/report/calc/:reportId(\\d+)',
name: 'CreateCalcPage',
component: () => import('@/pages/report/calc.vue'),
props: true, // 通過 props 傳遞路由參數(shù)
}
組件中使用 defineProps
<template>
<div>
<p>Project ID: {{ projectId }}</p>
<p>Report ID: {{ reportId }}</p>
</div>
</template>
<script setup>
import { defineProps } from 'vue';
const props = defineProps({
projectId: {
type: String,
required: true,
},
reportId: {
type: String,
required: true,
},
});
</script>
2. 通過 query 參數(shù)傳遞
可以通過 query 參數(shù)傳遞數(shù)據(jù)。在這種情況下,需要手動從 route 對象中獲取參數(shù)。
路由跳轉
router.push({
name: 'CreateCalcPage',
query: {
projectId: '123',
reportId: '456',
},
});
組件中使用 useRoute
<template>
<div>
<p>Project ID: {{ projectId }}</p>
<p>Report ID: {{ reportId }}</p>
</div>
</template>
<script setup>
import { useRoute } from 'vue-router';
const route = useRoute();
const projectId = route.query.projectId;
const reportId = route.query.reportId;
</script>
3. 通過 props 選項傳遞
可以在路由配置中使用 props 選項來傳遞靜態(tài)或動態(tài)參數(shù)。
靜態(tài)參數(shù)
{
path: '/report/calc',
name: 'CreateCalcPage',
component: () => import('@/pages/report/calc.vue'),
props: { projectId: '123', reportId: '456' },
}
動態(tài)參數(shù)
{
path: '/report/calc',
name: 'CreateCalcPage',
component: () => import('@/pages/report/calc.vue'),
props: route => ({ projectId: route.query.projectId, reportId: route.query.reportId }),
}
組件中使用 defineProps
<template>
<div>
<p>Project ID: {{ projectId }}</p>
<p>Report ID: {{ reportId }}</p>
</div>
</template>
<script setup>
import { defineProps } from 'vue';
const props = defineProps({
projectId: {
type: String,
required: true,
},
reportId: {
type: String,
required: true,
},
});
</script>
總結
- 通過
path參數(shù)傳遞:在路由路徑中定義動態(tài)參數(shù),并使用props: true將其作為 props 傳遞。 - 通過
query參數(shù)傳遞:在路由跳轉時通過query參數(shù)傳遞數(shù)據(jù),并在組件中使用useRoute獲取。 - 通過
props選項傳遞:在路由配置中使用props選項傳遞靜態(tài)或動態(tài)參數(shù)。
到此這篇關于栽Vue3中傳遞路由參數(shù)的三種方式的文章就介紹到這了,更多相關Vue3傳遞路由參數(shù)內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

