将对象作为参数传递给 router.push (vue-router@4.05) [英] Pass an object as param to router.push (vue-router@4.05)

查看:94
本文介绍了将对象作为参数传递给 router.push (vue-router@4.05)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

router.push({name:Order", params: {obj: {}})推送 obj: {} 失败,路由接收 obj: '[object Object]'

router.push({name:"Order", params: {obj: {}}) fails to push obj: {}, instead the route receives obj: '[object Object]'

我有这样的路线设置

{
    path: '/Order',
    name: 'Order',
    component: () => import("../views/Order.vue"),
    props: route => {
      return route.params.obj //  '[object Object]'
    },
 }

这导致在 Order.vue

{
    ...
    props: route => {
      return route.params.obj //  '{}'
    },
}

基于这个答案对象在旧版本中工作

Based on this answer objects work in older versions

我使用 jest 检查了传递给 router.push 的参数,它们看起来应该是:{name:Order", params: {obj: {}}

I've used jest to inspect the arguments passed to router.push and they appear as they should: {name:"Order", params: {obj: {}}

有什么想法吗?

推荐答案

将对象传递给 params从未支持 Vue-router

Passing objects to params was never supported in Vue-router

它在 Router v3 中使用 $router.push 工作 - 目标组件接收到对象.但是一旦用户开始使用浏览器导航(后退按钮)或复制/粘贴 URL,此解决方案就被破坏了(您可以尝试 这里 - 只需点击按钮,然后使用框架的后退和前进控制)

It sort of worked in Router v3 with $router.push - the target component received the object. BUT as soon as user started using browser navigation (Back button) OR copy/pasting URL's, this solution was broken (you can try it here - just click the button and then use back and forward controls of the frame)

根据经验 - 如果您想将任何内容传递给目标路由/组件,必须将此类数据定义为路由定义中的参数,以便可以将其直接包含在 URL 中.替代方案是在存储中传递数据、查询参数(对象需要使用 JSON.stringify 进行序列化)或使用历史状态.

As a rule of thumb - if you want to pass anything to the target route/component, such data must be defined as parameters in the route definition so it can be included directly in the URL. Alternatives are passing data in a store, query params (objects needs to be serialized with JSON.stringify), or using the history state.

这对于 Vue-router v3 是正确的,并且仍然适用于 Vue-router v4

This was true for Vue-router v3 and is still for Vue-router v4

注意

只是为了解释替代方案.通过商店"我的意思不只是 Vuex.我知道 Vuex 对于一些小型应用程序来说可能有点矫枉过正.与现有的 Vuex 相比,我个人更喜欢 Pinia.你可以很容易地创建全局状态解决方案你自己使用组合 API...

Just to explain alternatives. By "store" I do not mean just Vuex. I understand Vuex can be overkill for some small applications. I personally prefer Pinia over existing Vuex. And you can create global state solution yourself with composition API very easily...

这篇关于将对象作为参数传递给 router.push (vue-router@4.05)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆