You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 07:01:19