【问题标题】:Missing requried props when using beforeEnter() route guard使用 beforeEnter() 路由保护时缺少必需的道具
【发布时间】:2019-01-26 22:29:08
【问题描述】:

我正在尝试使用 beforeEnter() 路由保护从 API 获取数据,但出现错误:

Missing required prop: "rides"

这是我的代码。

router.js

{
   path: '/',
   name: 'home',
   component: () => import('./components/main.vue'),
   props: true,
   beforeEnter(to, from, next) {
     store.dispatch('ride/fetchRides').then(rides => {
       to.params.rides = rides
       next()
     })
   }
}

actions.js

fetchRides({ commit, dispatch }) {
    return statistcsService.ridesForCurrentWeek()
      .then(response => {
        commit('SET_RIDES', response.data)
        return response.data
      })
      .catch(error => {
        const notification = {
          type: 'danger',
          message: 'There was a problem fetching your rides'
        }
        dispatch('notification/add', notification, { root: true })
        throw error
      })
  }

Index.vue

<script>
    export default {
      props: {
        rides: {
          type: Array,
          required: true
        }
      }
    ...
  }
</script>

我错过了什么?道具设置在组件中,所以我不确定它为什么会哭。 我已验证 100% 我从 API 响应中获取数据。

【问题讨论】:

  • 您似乎已经在使用 vuex 是否有任何理由将其作为道具从路由器传递,而不是访问组件内 SET_RIDES 的状态?
  • 是的,我想在加载数据时显示NProgress 进度条和微调器。为了实现这一点,我需要删除我的组件和 VueX 之间的依赖关系,以便我可以在 beforeEnter() 路由保护上获取数据,然后将数据作为 props 发送到组件。否则,将在进度条和微调器显示之前,在created() 生命周期挂钩上获取数据。
  • @Gowri 如果您需要查看更多代码,这是我的源代码github.com/jedrekdomanski/bikeramp-front
  • 也许您忘记在该组件的 html 代码中添加 rides 属性?根据错误消息 - 这就是问题所在。
  • @jedi,我没有看到任何设置了 rides 属性的组件。 :rides=... 的 HTML 组件在哪里?

标签: vue.js vuex vue-router


【解决方案1】:

您忘记在该组件的 html 代码中添加 rides 属性。根据错误信息 - 这就是问题所在。

例子:

<component :rides="rides"></component>

【讨论】:

  • 我没有想到从 params 接收 props 的组件是 /components/main.vue 并且我还需要在那里设置 props rides。这个答案和之前的评论让我找到了问题的根本原因并帮助我解决了它。谢谢。
猜你喜欢
  • 2018-10-21
  • 2018-03-17
  • 1970-01-01
  • 1970-01-01
  • 2019-11-11
  • 2019-04-23
  • 2019-04-21
  • 2015-02-14
  • 2014-03-09
相关资源
最近更新 更多