Vue3 + vite-plugin-pages:命名路由传可选对象Prop问题及优化
编辑:刚意识到这是一种反模式,因此我将研究替代解决方案,可能会使用Pinia来存储要传递的对象。
Vue 3项目配置:
- 说明:该项目同时使用
unplugin-vue-components和unplugin-auto-import,因此部分文件中没有导入语句。
src/main.ts
import { createApp } from "vue"; import { createRouter, createWebHashHistory } from "vue-router"; import App from "./App.vue"; import routes from "~pages"; // router const router = createRouter({ history: createWebHashHistory(), routes, linkActiveClass: "active", scrollBehavior(to, from, savedPosition) { if (savedPosition) return savedPosition; return { top: 0 }; }, }); const app = createApp(App); app.use(router); app.mount("#app");
App.vue
<script setup lang="ts"></script> <template> <div id="viewport"> <RouterView /> </div> </template>
src/pages/examples/index.vue
- 可通过
http://localhost:8080/#/examples访问
<script setup lang="ts"> import { reactive, ref, inject, onMounted } from "vue"; interface Example { id: number, name: string; } const examples = ref<Example[]>([ { id: 1, name: "Example object name 1", }, { id: 2, name: "Example object name 2", }, ]); </script> <template> <table> <tbody> <router-link v-for="e in examples.value" :key="e.id" v-slot="{ navigate }" :to="{ path: `/examples/${e.id}`, params: { example: e }, }" custom > <tr role="button" @click="navigate"> <td> {{ e.id }} </td> </tr> </router-link> </tbody> </table> </template>
src/pages/examples/[id].vue
- 可通过
http://localhost:8080/#/examples/1访问
<script setup lang="ts"> import { ref, inject, onMounted } from "vue"; interface Props { id: number; name: string | undefined; } const props = defineProps<Props>(); </script> <template> <div> {{ props.id }} </br> {{ props?.name }} </div> </template>
目前上述代码可运行,但出现以下错误(且可选Prop e未传递到[id].vue):
[Vue Router warn]: Path "/examples/1" was passed with params but they will be ignored. Use a named route alongside params instead.
- 来自
vue-router.mjs
内容的提问来源于stack exchange,提问作者Rio Weber
相关产品推荐
相关产品推荐

