Vue-router4 - 使用 <router-link :to> 传递对象不会传递动态数据

Nik*_*kOs 1 javascript vue.js vue-props vue-router4

我浏览了这个vue-router@4.05 对象参数,它有些相关。该线程中提到了这个https://github.com/vuejs/vue-router-next/issues/494,但我仍然很困惑。

我还尝试使用路由器链接组件的:to属性传递一些数据。我做了两支笔来展示这个问题:

Pen 1成功传递了在路由定义中定义的对象。

Pen 2尝试传递一个动态对象,但它获取的是一个带有 [Object object] 的字符串,而不是实际对象,如 github 问题中所述。

控制台输出:

[Vue warn]:无效的道具:道具“存储库”的类型检查失败。预期对象,得到具有 > 值“[object Object]”的字符串。at <Repository repository="[object Object]" onVnodeUnmounted=fn ref=Ref > at at at

所以,如果我明白这一点,最终你不能传递一个动态对象,因为它被解析了,但你可以传递一个静态对象?

我尝试过使用 props: true 和一切,我正在尝试将功能模式解决方案作为更复杂的示例

片段:

    <router-link :to="{ name: 'Home' }">Home</router-link>
    <router-view />
Run Code Online (Sandbox Code Playgroud)
    <router-link
      :to="{
        name: 'Repository',
        params: { repository: { one: '1', two: '2' } },
      }">click me</router-link>
Run Code Online (Sandbox Code Playgroud)

v1

    const routes: Array<RouteRecordRaw> = [
    {
      path: "/",
      name: "Home",
      component: Home
    },
    {
      path: "/repo/",
      name: "Repository",
      component: () => import("../components/Repository.vue"),
      props: (route) => {
        console.log("entered route");
        console.log(route);
        return { ...route.params, repository: { one: "1", two: "2" } };
      }
    }];
Run Code Online (Sandbox Code Playgroud)

v2

    const routes: Array<RouteRecordRaw> = [
    {
      path: "/",
      name: "Home",
      component: Home
    },
    {
      path: "/repo/",
      name: "Repository",
      component: () => import("../components/Repository.vue"),
      props: (route) => {
        console.log("entered route");
        console.log(route);
        return { ...route.params };
      }
    }];
Run Code Online (Sandbox Code Playgroud)

UX *_*dre 5

您的代码中发生了什么:

正如您在控制台中的警告消息中看到的,您实际上是String从 prop 获取的,而不是Object

[Vue warn]:无效的道具:道具“存储库”的类型检查失败。期望的对象,得到字符串

许多人建议使用Vuex并设置全局状态作为解决方案,我相信这不是您想要的。

解决方案

为了避免获取[Object, Object]传递的数据,您可以做的是在原始页面中对对象进行字符串化,然后在目标页面上再次将传递的字符串解析为对象。

原始页面/路由器组件

 <router-link
      :to="{
        name: 'Your_Route_Name',
        params: { repository: JSON.stringify({ one: '1', two: '2' }) },
      }">click me</router-link>

Run Code Online (Sandbox Code Playgroud)

在您的目标路由器组件中

<template>
    <div>
        {{ JSON.parse(repository) }}
    </div>
</template>

<script>
export default {
    props: ["repository"],
    setup(props) {
        //Log the parsed object in console. Example shown with Vue3 Composition API but you get the idea.
        console.log(JSON.parse(props.customer));
    }
}
</script>

Run Code Online (Sandbox Code Playgroud)

这样,您将能够按预期传递对象。