1捶牢、定義路由
在工程文件router\index.js中定義路由如下:
import { createRouter, createWebHashHistory } from "vue-router";
const routes = [
{
path: '/caseinfoeditor/:caseId',
component: () => import('../views/system/caseinfoeditor.vue')
}
];
const router = createRouter({
history: createWebHashHistory(),
routes
});
export default router;
其中:caseId是定義路由參數(shù)的占位符。
2巍耗、在組件中獲取路由參數(shù)的方法
<script setup name="Welcome">
import { onMounted } from 'vue';
import { useRouter } from 'vue-router';
const $router = useRouter();
onMounted(() => {
console.log('$router:', $router.currentRoute.value.params.caseId);
});
</script>
注意這里使用了vue3的setup語法糖秋麸。如果是非vue3 setup語法糖,useRouter和useRoute函數(shù)不能在setup里面的函數(shù)體內(nèi)部執(zhí)行炬太,要放在頂部或者其他位置灸蟆,不然作用域改變,執(zhí)行后的router/route是 undefined亲族。