Vue.js,如何将数据传递到另一个路由的组件中?

15

对于Vue.js初学者来说,将数据从一个页面传递到另一个页面是一个简单的任务,但却变成了一个真正的头痛问题。

这是我的路由器enter image description here

我在“/”页面上呈现一个表单,该表单发出API请求。enter image description here

我只想将数据传递到另一个路由页面,使用另一个组件enter image description here

在Vue中做到这点真的很难吗?今天让我非常头痛。获取API数据,保存并发送到另一个组件。我该怎么做?


你想传递什么数据?是 activities 吗? - choasia
4个回答

16

正如Antony所说,由于您已经在router/index.js中启用了props,因此可以像这样在router.push中传递参数:


router.push({
    name: 'events',
    params: {
        items: data
    }
});

那么你就能够在 EventsDisplay.vue 组件中通过 props 接收 items

export default {
    name: 'eventsDisplay',
    props: ['items'],
};

1
@EzhiMakov this.items 应该可以工作。由于它与这个问题无关,您可以打开另一个问题并将您的代码粘贴在那里。 - choasia
非常感谢,抱歉之前的评论,是我在刷新/事件页面时没有传递数据的愚蠢行为。 - Evgeny Malkov
谢谢,它确实起作用了。浪费了这么多时间,终于搞定了。 - Ramesh_D
@choasia,我可以请你看一下关于GitHub源代码与Anthone Gore的《Full-Stack Vue.js 2和Laravel 5》书籍相关的Vue.JS问题吗?链接在这里:https://stackoverflow.com/questions/59245577/laravel-vuejs-router-view-does-not-render-the-component?特别是看一下OP的EDIT:部分。 - Istiaque Ahmed
2
在我的情况下(@vue/cli-service版本3.12.1),我无法通过props获取参数,但我可以从this.$route.params.items获取它。 - juacompe
请在路由属性定义中添加 "props: true",如下所示 => { path: "/dataList", name: "dataList", props: true, meta: { title: "数据列表" }, component: () => import("路径到数据列表组件") } - Wasi Sadman

2
如果您想要全局保存它,您可以使用事件总线或 VueX 存储来包含它,然后在需要访问它时,从这个事件总线或存储中保存和加载它。
如果您只想在这两个组件之间传递它,并且只有在从第一个页面访问第二个页面时才传递它,您可以按照此指南将属性传递给路由参数:https://router.vuejs.org/en/essentials/passing-props.html

1
尝试使用 Vuex 在源组件中
this.$store.commit('changeDataState', this.$data);
this.$router.push({name: 'user-post-create'});

在目标组件中。
created () {
    console.log('state', this.$store);
    this.$store.getters.Data;
}

0
在你的Vue路由器中添加props true。

{
    path: "/pay-now",
    name: "pay",
    props: true,
    component: () =>
      import(/* webpackChunkName: "about" */ "../components/account/pay.vue"),
    beforeEnter: AuthGuard,
  },

然后像这样通过路由传递props

        this.$router.push({ 
        name: "pay",
        params: {
        result:this.result,
      }
      });


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接