首页 > 解决方案 > id passed through params get lost on page refresh

问题描述

I have a component called Subscribers that receives props via params from another component called Details. I use the props received to make an API call to get the list of subscribers. This works well.

But an issue arises when the page is refreshed. The id that is passed via params is lost - becomes null. Cause of that subscribers which is defined as an empty array in data becomes undefined as seen in this error:

TypeError: Cannot read property 'length' of undefined

This is how I am passing the params from Details component

<router-link class="unsubscribe" :to="{ name: 'fund-subscribers', params: {fundProp: fund, id: fund.id } }">View all subscribers to this fund</router-link>

Then I have this:

props: {
  fundProp: {
    type: Object,
    default() {
      return {
        id: null,
        title: '',
        description: ''
      };
    }
  },
},
data() {
  return {
    fund: this.fundProp,
    subscribers: [],
  }
},

Here is the route configuration code for fund-subscribers

{
  path: 'funds/:id/subscribers',
  name: 'fund-subscribers',
  component: Subscribers,
  meta: {
    title: 'Admin'
  },
  props: true
},

What could I be doing wrong?

标签: vue.jsparameters

解决方案


所以我找到了解决它的方法。首先,没有必要通过fundProp,我只能将idvia 参数传递给router-link

<router-link class="unsubscribe" :to="{ name: 'fund-subscribers', params: { id: fund.id } }">
  View all subscribers to this fund
</router-link>

完成后,我现在可以使用this.$route.params.id. 我可以在我的组件数据中设置我的资金,然后用它来进行 API 调用。

data() {
  return {
    fund: this.$route.params.id
  }
},

向服务器发出请求的函数可以使用此路径: /funds/${fund}/users,而不是/funds/${fund.id}/users

我希望这对以后的人有帮助(将来也对我有帮助)。

为了更好地理解它,请使用以下链接:

https://forum.vuejs.org/t/route-params-not-showing-after-full-page-refresh/30364

https://router.vuejs.org/en/advanced/data-fetching.html


推荐阅读