如何使用 Vue 3 将对象作为 props 传递给 Vue Router?

问题描述 投票:0回答:3

如何使用 Vue Router 在 Vue 3 中将对象作为 props 传递?这可以在 Vue 2 中按照接受的答案 here 及其相应的 JSFiddle 来实现。在 Vue 3 中,与 Vue 2 相比,此语法将推送的对象字符串化为“[object Object]”。我在下面的fiddle中尝试过使用 Vue 3。

const Home = { template: '<div>Home</div>',
               mounted: function() {
                this.$router.push({
                    name: "about",
                    params: {
                        user: "User Name",
                        objectParam: {a: "a"}
                    }
                  })
                }}
const About = { template: '<div>About</div>',
                                props: ['user', 'o', 'objectParam'],
                mounted: function(){
                    console.log( "Passed props:" )
                    console.log( this.$props )
                }}

const routes = [
  { path: '/', component: Home },
  { path: '/about', name:"about", component: About, 
                                  props: route => (
                                         console.log("Params defined here are passed as objects."),
                                         console.log("But route params object passed via push has already been stringified."),
                                         console.log(route.params),
                                         {o: {b: "b"},
                                          ...route.params
                                          })},
]


const router = VueRouter.createRouter({
  history: VueRouter.createWebHashHistory(),
  routes,
})

const app = Vue.createApp({})
app.use(router)
app.mount('#app')

Vue 3 中可以通过 Vue Router Push() 传递对象吗?

vue.js vue-router vuejs3
3个回答
1
投票

我找不到 Vue Router 的任何官方文档来支持这一点,说实话,我认为将动态对象作为参数发送不是一个好主意,但如果你真的想这样做,实现它的一种方法是对您的对象进行字符串化,然后在接收方解析它。所以像这样:

this.$router.push({
    name: "about",
    params: {
        user: "User Name",
        objectParam: JSON.stringify({ a: "a" })
    }
})

然后在另一个组件中:

JSON.parse(this.$route.params.objectParam)

0
投票

我敢说我认为这在 Vue3 中是不可能的。

您可以查看像 Vuex 这样的状态管理器,看看它是否可以解决您的问题。状态管理器概念将允许您在多个视图中保留一个复杂的对象。


0
投票

还有一点需要注意,除了字符串化之外,如果我们现在在 Vue3 中从 Vuex 获取这个对象我们将获得一个代理。这也带来了麻烦。

为了解决这个问题,我们需要首先将 proxy 转换为普通对象,例如使用 lodash

cloneDeep

router.push({
  params: {
    objFromVuex: JSON.stringify(cloneDeep(objFromVuex))
  }
});

要读取该值,只需

JSON.parse

const objFromVuex = JSON.parse(this.$route.params.objFromVuex);
© www.soinside.com 2019 - 2024. All rights reserved.